Nested For Loop With Example


Explanation

A nested for loop is a loop placed inside another for loop. In this program, the outer loop controls the rows, while the inner loop prints the value of the row number repeatedly. As a result, each row contains the same number, and the value changes only when the outer loop moves to the next row.

How It Works?

  • Step 1: Declare integer variables r and c.
  • Step 2: Start the outer for loop with r = 1.
  • Step 3: For each row, start the inner for loop with c = 1.
  • Step 4: Print the value of r followed by a space.
  • Step 5: Repeat until c <= 5.
  • Step 6: Print a new line after completing each row.
  • Step 7: Continue 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 ", r);

        }

        printf("\n");

    }

    getch();

}


Output

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

Practice Exercises

Task 1: Write a C program using nested for loops to print the row number 4 times for 4 rows.

Goal: Learn how the outer loop controls the row number while the inner loop repeats the same value multiple times.

💡 Hint: Use two variables r and c. Run both loops from 1 to 4. Print the value of r 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 <= 4; r++)
    {

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

            printf("%d ", r);

        }

        printf("\n");

    }

    getch();

}


Output
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
Explanation: The outer for loop controls the row number, while the inner for loop prints the value of r four times in each row. After completing one row, a new line is printed, and the process repeats until all four rows are displayed.