nested for loop in c programming examples

nested for loop in c programming examples

Nested for loop in c programming examples

    As the name suggests Nested for loop means a loop inside a  loop. For this reason, Nested loops are also called "loop inside a loop". There is no limit to defining a loop inside a loop. There can be defined 'n' number of loops. The C programming language supports the nesting of loops. Let's understand this concept by syntax and examples given below.

to understand this concept required skill:

Syntax of Nested For loop:

for(initilization ; condition; increment or decrement) // outer loop
{
    //loop_statements
    for(initilization ; condition; increment or decrement) // inner loop
   {
     //loop_statements
   }
}
    The above Syntax is for one for loop inside another for a loop. But there can be 'n' number loops. The Syntax is given below.

for(initilization ; condition; increment or decrement) 
{
  // loop_statements
   for(initilization ; condition; increment or decrement) 
   {
     //loop_statements
     for(initilization ; condition; increment or decrement) 
     {
     //loop_statements
      for(initilization ; condition; increment or decrement) 
      {
        //loop_statements
        for(initilization ; condition; increment or decrement) 
        {
          //loop_statements
          ....... upto n numbers
        }
      }
     }
   }
}


Nested for loop flow chart

Nested For loop flow chart

Let's understand the data flow from the above flowchart. First, the outer loop condition is checked and if the condition is true then the inner loop will execute else the loop will be terminated. Now lets's come to the inner loop if the inner loop condition is true then the inner loop body will be executed else the inner loop will be terminated and it will go again to the outer loop for checking the condition and this process will remain to continue until the loop condition becomes false.


Examples of Nested for loop in c 

let's understand this nested for loop concept with very simple and easy examples

Example 1:

Write a c programme to print 
1
12
123
1234
12345

#include <stdio.h>

int main() {
  for (int i=1;i<=5;i++)
 {
   for(int j=1;j<=i;j++)
   {
     printf("%d",j);
   }
    printf("\n");
 }
  return 0;
}

Example 2

write a c program to print the star pattern
*
* *
* * *
* * * *
* * * * *

#include <stdio.h>

int main() {
  for (int i=1;i<=5;i++)
 {
   for(int j=1;j<=i;j++)
   {
     printf("*");
   }
    printf("\n");
 }
  return 0;
}

Example 3

write a programme in c to print a 2d array (where int arr[2][2])

#include <stdio.h>
int arr[2][2] ={{1,2},{3,4}};
int main() {
  for (int i=0;i<2;i++)
 {
   for(int j=0;j<2;j++)
   {
     printf("%d\n",arr[i][j]);
   }
 }
  return 0;
}

1
2
3
4

Post a Comment

0 Comments