Nested Loop (Loop Within A Loop)


Explanation

A nested loop means a loop inside another loop. In this program, the outer for loop controls the number of rows, while the inner for loop prints the numbers from 1 to 5 in each row. The process is repeated until all 5 rows are displayed.

How It Works?

  • Step 1: Declare integer variables r and c.
  • Step 2: The outer for loop starts with r = 1 and runs until r <= 5.
  • Step 3: For every row, the inner for loop starts with c = 1 and runs until c <= 5.
  • Step 4: Print the value of c followed by a space.
  • Step 5: After the inner loop finishes, print a new line.
  • Step 6: Repeat the process until all 5 rows are printed.

Example Program



#include <stdio.h>
#include <conio.h>


main()
{

    int r, c;

    clrscr();

    for(r = 1; r <= 5; r++)
    {

        for(c = 1; c <= 5; c++)
        {

            printf("%d ", c);

        }

        printf("\n");

    }

    getch();

}


Output

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

Practice Exercises

Task 1: Write a C program using nested for loops to print the numbers from 1 to 3 in 3 rows.

Goal: Learn how to use nested for loops to print a number pattern using rows and columns.

💡 Hint: Use two variables r and c. Run both loops from 1 to 3. Print c inside the inner loop and print a new line after each row.
💡 Show Solution


#include <stdio.h>
#include <conio.h>


main()
{

    int r, c;

    clrscr();

    for(r = 1; r <= 3; r++)
    {

        for(c = 1; c <= 3; c++)
        {

            printf("%d ", c);

        }

        printf("\n");

    }

    getch();

}


Output
1 2 3
1 2 3
1 2 3
Explanation: The program uses two nested for loops. The outer loop controls the rows, while the inner loop prints the numbers from 1 to 3 in each row. After completing one row, a new line is printed, and the process repeats until all three rows are displayed.