C Programming Tutorial - ITDeveloper

ITDeveloper : C Programming

C Programming

Step by Step Tutorials


Share with a Friend

Nested Loops in C

A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.

 

Nested Loop refers to a loop within a loop, as the name implies. Within a loop, there can be any number of loops. We're all familiar with looping conditions such as for, while, and do-while. To create nested loops, we can loop multiple types of loops within one other. Nested Loops are supported by the C programming language.

 

1. Nested for Loop

Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the equivalent flow diagram for nested ‘for’ loops:

 

Syntax: The syntax for nested for loop is shown below.

for ( initialization; condition; increment/decrement ) {

for ( initialization; condition; increment/decrement ) {

// block of statement(s) of inside loop
}

// block of statement(s) of outer loop
}

Flow chart: The flow chart for the nested for loop is shown below.

Nested for loop

Example: An annual examination in m subjects is given to a class of n students. A program that takes each student's marks in various subjects and calculates and prints the overall grade for each of them.

#include <stdio.h>

#define FIRST 360
#define SECOND 240

int main()

 {
     int n, m, i, j;
     int roll_number, marks, total;
     printf("Enter number of students and subjects\n");
     scanf("%d %d", &n, &m); // number of students and subjects
     printf("\n");
     for (i = 1; i <= n; i++)

       {
           printf("Enter roll number of student : ");
           scanf("%d", &roll_number); // roll number of particular student
           total = 0;
           printf("\nEnter marks of %d subjects for Roll No %d\n", m, roll_number);
           for (j = 1; j <= m; j++)

             {
                  scanf("%d", &marks); // marks for each subject for particular student
                  total = total + marks;
            }
           printf("TOTAL MARKS = %d ", total);
           if (total >= FIRST) // comparison with the marks required for first Division
               printf("( First Division )\n\n");
           else if (total >= SECOND) // comparison with the marks required for second Division
                     printf("( Second Division )\n\n");
                 else // if both of the above condition fails, it means that the student has failed.
                     printf("( *** F A I L *** )\n\n");
       }
 }


Output:

Enter number of students and subjects
3 6

Enter roll number of student : 21609

Enter marks of 6 subjects for Roll No 21609


88 99 76 56 83 92

TOTAL MARKS = 494 ( First Division )

Enter roll number of student : 21608

Enter marks of 6 subjects for Roll No 21608


34 45 23 56 60 12


TOTAL MARKS = 230 ( *** F A I L *** )

Enter roll number of student : 21607

Enter marks of 6 subjects for Roll No 21607


35 44 33 66 50 12
TOTAL MARKS = 240 ( Second Division )

2. Nested While Loop

Syntax: The syntax for a nested while loop is shown below.

while(condition)

   {

      while(condition)

        {

            // block of statement(s) of inside loop
        }

      // block of statement(s) of outer loop
  }

Flow chart: The flow chart for a nested while loop is shown below.

Nested while loop

Example:The example for a nested while loop is shown below.

A program to print the 2-dimensional array using a while loop.

 


#include<stdio.h>

int main()

  {
      int rows, cols;
      int count = 1;
      printf("Enter the number of rows: ");
      scanf("%d", &rows);
      printf("Enter the number of columns: ");
      scanf("%d", &cols);

      // 2d array declaration
       int a[rows][cols];
       int i = 1;

      // outer loop begins
      while (i <= rows)

       {
           int j = 1;

          // inner loop begins
             while (j <= cols)

               {
                   printf("%d\t", count);
                   count++;
                   j++;
               }
             i++;
            printf("\n");
       }
 }

Output:

Enter the number of rows: 3
Enter the number of columns: 3


1 2 3
4 5 6
7 8 9

3. Nested Do-while Loop


Syntax: The syntax of a nested do-while loop is shown below.
do{

   do{

            // block of statement(s) of inside loop

       }while(condition);

      // block of statement(s) of outer loop

 }while(condition);

Flow chart: The flow chart of a nested do-while loop is shown below.

Nested do...while loop

Example: The example of a nested do-while loop is shown below.


A program to print the multiplication table from 1 x 1 to 10 x 10.


#include <stdio.h>
#define COLUMNX 10
#define ROWMAX 10


int main()
{
   int row, column, y;
   row = 1;
   printf(" MULTIPLICATION TABLE \n");
   printf("------------------------------------------\n");
  // outer loop begins
  do
   {
       column = 1;
       // inner loop begins
       do
         {
             y = row * column;
             printf("%4d", y);
             column = column + 1;
         } while (column <= COLUMNX); // inner loop ends
        printf("\n");
        row = row + 1;
   } while (row <= ROWMAX); // outer loop ends
   printf("------------------------------------------\n");
}

Output:


MULTIPLICATION TABLE
------------------------------------------
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
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
------------------------------------------


More Examples of Nested Loop in C

Example 1

A C Program to print solid, hollow patterns using nested for loop.

#include <stdio.h>

int main()

  {
      int rows, columns;
      printf("Enter the number of rows: ");

      // taking input for number of rows
      scanf("%d", &rows);

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

      // taking input for number of columns
      scanf("%d", &columns);

      // Outer loop to handle number of rows
      for (int i = 1; i <= rows; i++) {
           // Inner loop to handle number of columns
          for (int j = 1; j <= columns; j++) {
              // Printing stars
              printf("@ ");
           }

         // Ending line after each row
        printf("\n");
     }
 return 0;
}

Output:

Enter the number of rows: 5

Enter the number of columns: 5

@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @
@ @ @ @ @

Example 2

Pyramid pattern of number using nested while loop.

#include <stdio.h>

int main()

  {
      int i, num, k;
      printf("Enter number here: ");
      scanf("%d", &num);
      i = 1;
      while (i <= num)

        {
             printf("\n");
             k = 1;
             while (k <= i)

               {
                   printf("%d ", k);
                   k = k + 1;
               }
              i = i + 1;
         }
        return 0;
   }

Output:

Enter number here: 5

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

Example 3

A C program using a nested do-while loop.

#include <stdio.h>

int main()

 {
     int x = 1;
     // outer loop begins
     do {
           int y = 1;
           // inner loop begins
           do {
                printf("%d %d", x, y);
                printf("\n");
                y++;
              } while (y <= 3); // inner loop ends
           x++;
       } while (x <= 3); // outer loop ends
 }

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Example 4

A C Program to print pascal triangle using nested for loop.

#include <stdio.h>

int main()

  {
      int rows, coef = 1, space, i, j;
      printf("Enter the number of rows: ");

      // taking input for number of rows
      scanf("%d", &rows);

      // Outer loop to handle number of rows
      for (i = 0; i < rows; i++)

          {
              // loop to handle space
             for (space = 1; space <= rows - i; space++)

                 // Printing Space
                 printf(" ");

            // Inner loop to handle number of columns
            for (j = 0; j <= i; j++)

               {
                  if (j == 0 || i == 0)
                     coef = 1;
                  else
                     coef = coef * (i - j + 1) / j;
                  printf("%4d", coef);
               }

            // Ending line after each row
            printf("\n");
       }
    return 0;
 }

Output:

Enter the number of rows: 5

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1