C Nested Loops Syntax And Examples

In the C programming language, it is permissible to nest multiple loops within one another without any limitations on the depth of nesting. The nesting level can be set to any value 'n' as needed by the program. The outermost loop in the nested structure dictates the overall number of iterations, while the inner loops run through their complete cycles for each iteration of the outer loop.

Syntax of Nested Loop

It has the following syntax:

Example

Outer_loop  

{  

    Inner_loop  

   {  

         // inner loop statements.  

   }  

       // outer loop statements.  

}

Types of Nested Loop

The C programming language supports nesting of all loop types. These loops can be used with several loops, such as:

  • For Loop
  • While Loop
  • Do-while Loop

Here, we will explore these loops sequentially by utilizing nested loops.

Nested for loop

In C programming, the nested for loop is a loop that includes one for loop within another. The inner loop executes completely for each iteration of the outer loop, making it beneficial for tasks like generating patterns, constructing multiplication tables, or handling fixed-size 2D arrays.

Syntax

It has the following syntax:

Example

for (initialization; condition; update)   

{  

    for(initialization; condition; update)  

    {  

           // inner loop statements.  

    }  

    // outer loop statements.  

}

Simple C Nested for loop Example

Here, we will illustrate the concept of a nested for loop in C programming through an example.

Example

Example

#include <stdio.h>



int main()  

{  

    int n; // variable declaration  

    printf("Enter the value of n: ");  

    scanf("%d", &n);  // taking input from the user



    // Displaying the n tables  

    for(int i = 1; i <= n; i++)   // outer loop  

    {  

        for(int j = 1; j <= 10; j++)  // inner loop  

        {  

            printf("%d\t", (i * j));  // printing the value  

        }  

        printf("\n");  

    }  

    return 0;

}

Output:

Output

Enter the value of n: 3

1 2 3 4 5 6 7 8 9 10	

2 4 6 8 10 12 14 16 18 20	

3 6 9 12 15 18 21 24 27 30

Explanation:

In this particular instance, we exhibit multiplication tables through the utilization of a nested for loop. Initially, the external for loop iterates from 1 to n, with each iteration of i symbolizing the integer for which the multiplication table is being generated. Subsequently, the internal for loop iterates from 1 to 10, displaying the results of multiplying that particular number by integers ranging from 1 to 10.

For each iteration of i, the nested loop iterates through j values from 1 to 10, printing the product of i and j consecutively. This process effectively generates a full row of the multiplication table corresponding to the current value of i. Upon completion of the inner loop, the outer loop increments to the next i value, repeating the process until the program outputs multiplication tables ranging from 1 to n.

Nested While Loop

In C programming, a nested while loop is a loop that includes one while loop within another. Initially, the outer loop evaluates its condition. When the condition is met, it proceeds with the execution of the outer loop. Subsequently, the inner loop iterates as long as its condition is satisfied. This nesting feature enables us to control the iterations or loop cycles based on conditions rather than a predefined count.

Syntax:

It has the following syntax:

Example

while(condition)  

{  

    while(condition)  

    {  

         // inner loop statements.  

    }  

// outer loop statements.  

}

C Nested While Loop Example

Let's consider an example to illustrate the nested while loop in the C programming language.

Example

Example

#include <stdio.h>  

int main()   // main function

{  

   int rows;  // variable declaration  

   int columns; 

   int k=1; // variable initialization  

   printf("Enter the number of rows: ");  // input the number of rows.  

   scanf("%d",&rows);  

   printf("\nEnter the number of columns: "); // input the number of columns.  

   scanf("%d",&columns);  

      int a[rows][columns]; //2d array declaration  

      int i=1;  

   while(i<=rows) // outer loop  

   {  

       int j=1;  

      while(j<=columns)  // inner loop  

       {  

           printf("%d\t",k);  // printing the value of k.  

           k++;   // increment counter  

           j++;  

       }  

       i++;  

       printf("\n");

   }

}

Output:

Output

Enter the number of rows: 3

Enter the number of columns: 4

1 2 3 4	

5 6 7 8

9 10 11 12

Explanation:

In this particular instance, a two-dimensional array will be populated and displayed by employing nested while loops. Initially, the external while loop will iterate based on the row count, while the internal while loop will iterate based on the column count. Within the inner loop, the value of 'k' will be printed and subsequently incremented after each print operation.

Once the inner while loop finishes displaying an entire row, the outer loop will proceed to the next row after outputting a newline character. This sequence will persist until the specified number of rows and columns has been printed, as determined by the user's input.

Nested do-while loop

In C programming, a nested do-while loop involves incorporating one do-while loop within another do-while loop. The primary advantage of utilizing this nested structure is that both loops are guaranteed to run at least once since the condition is evaluated at the end of each loop iteration. This nested approach proves particularly beneficial when initial steps must be executed before condition evaluation, like in scenarios involving pattern printing or iterative input processing.

Syntax

It has the following syntax:

Example

'do..while' loop.

do  

{  

   do  

  {   

      // inner loop statements.  

   }while(condition);  

// outer loop statements.  

}while(condition);

Simple C nested do-while loop Example

Let's consider an instance to demonstrate the nested do-while loop in the C programming language.

Example

Example

#include <stdio.h>  

int main()  

{  

  /*printing the pattern 

     ******** 

     ******** 

     ******** 

     ******** */  

int i=1;  

do           // outer loop  

{  

    int j=1;  

    do       // inner loop  

   {  

      printf("*");  

      j++;  

   }

while(j<=8);  

    printf("\n");  

    i++;  

     }

while(i<=4);  

}

Output:

Output

********

********

********

********

Explanation:

In this instance, a nested do-while loop has been employed to display a pattern of asterisks. Initially, the outer loop runs 4 times, corresponding to the 4 rows to be displayed. The inner loop places 8 asterisks on each row. Because the do-while loop runs at least once before condition evaluation, the inner loop commences printing asterisks immediately. Upon printing 8 asterisks, a new line is appended, and this process continues until all 4 rows are printed.

Conclusion

In summary, C provides support for nested loops, enabling the execution of one loop inside another to efficiently handle repetitive tasks in a multi-dimensional fashion. Nested loops prove beneficial for generating recurring patterns, manipulating matrices, or performing various iterations. While nested loops aid in minimizing code redundancy, excessive use may potentially impact performance.

Input Required

This code uses input(). Please provide values below: