Nested Loops in C


  • When one loop is used inside another loop then these loops are known as the nested loops.
  • We can use for loop inside another for loop, while loop inside another for loop, do-while loop inside another while loop or so on.
  • Here is syntax of nested loops in which we use for loop inside another for loop:
  • Syntax

    for(initialize counter;condition;increment/decrement counter)

    {

    for(initialize counter;condition;increment/decrement counter)

    {

    Statements;

    }

    Statements;

    }

    Here is an example of nested for loop :

    Example

    #include<stdio.h>

    #include<conio.h>

    int main()

    {

    int i=2,j=2;

    for(i=1;i<=2;i++)

    {

    printf("\ni=%d",i);

    for(j=1;j<=2;j++)

    {

    printf("\nj=%d",j);

    }

    }

    getch();

    return 0;

    }

    Output

    The output of the above program is as follows:

    i=1

    j=1

    j=2

    i=2

    j=1

    j=2