top

Search

C Tutorial

.

UpGrad

C Tutorial

Nested Loop in C

Programming is a world of loops, conditions, and functions. Among these, loops have a pivotal role in reducing the redundancy of the code. One such important loop structure is the nested loop in C. The art of implementing nested loops skillfully can add great value to your programming acumen.

Let’s explore the world of nested loops in C to understand their implementation accurately. This article will include the various types of nested loops along with their examples to help you tackle nested loop in C questions!

Definition of Nested Loops in C

In the C programming language, a loop inside another loop is called a nested loop. The first loop is often referred to as the outer loop, while the loop inside it is called the inner loop. Each time the outer loop runs, the inner loop runs completely, making nested loops a powerful tool when dealing with multi-dimensional data structures or repeating complex operations.

Importance of Nested Loops in Programming

Nested loops play a crucial role in programming, as they allow the implementation of complex algorithms and data manipulation techniques essential in real-world applications. Here's a look at why nested loops are important:

1. Multi-dimensional Data Handling

One of the main uses of nested loops is in handling multi-dimensional data structures like arrays and matrices. With the advent of big data, dealing with multi-dimensional data has become more common, and nested loops provide a straightforward way to access, manipulate, and traverse these data structures.

2. Implementing Algorithms

Several important algorithms in computer science, such as sorting algorithms (bubble sort, insertion sort) and search algorithms (linear search in 2D arrays), rely on nested loops for their implementation. 

3. Generating Patterns

Nested loops are widely used in graphics and game programming to generate complex patterns and structures. They are also frequently used in console programs to print patterns like star patterns, number patterns, and more.

4. Simulation and Modeling

Nested loops are used in simulations and modelling. For example, in physical simulations, a nested loop might be used to calculate the interactions between pairs of particles. In financial modelling, a nested loop could be used to run multiple scenarios with different variables.

5. Efficiency

While it's true that misuse of nested loops can lead to efficiency problems, when used correctly, they can also make code more efficient by eliminating the need for repeated code. A task that might require several separate loops can often be accomplished more efficiently with a single set of nested loops.

Flowchart of Nested Loop in C

Nested loops flow in a top-to-bottom manner. After the outer loop is initiated, the control enters the inner loop. The inner loop executes completely for each iteration of the outer loop. After the inner loop ends, the control returns to the outer loop as it moves to the next iteration, and the process repeats.

Types of Nested Loops

There are three primary types of nested loops: for, while, and do-while.

I. Basic Syntax

Format of Nested Loops

Here is the basic format of the nested loop in C: 

for(initialization; condition; increment/decrement) {
    for(initialization; condition; increment/decrement) {
        // Inner loop statements
    }
    // Outer loop statements
}

Examples of Simple Nested Loops

Here is a basic nested loop in C that prints a 2D matrix:

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

This code initiates a nested loop where the outer loop represents the rows, and the inner loop represents the columns. Thus, it prints a 3x3 matrix.

Explanation of Loop Control Statements (Break and Continue)

'Break' and 'continue' are control statements in C programming that are used to control the flow of loop execution. The 'break' statement terminates the loop, while the 'continue' statement skips the current iteration and moves to the next.

II. Nested Loops vs. Single Loops

Single loops are used when you want to repeat a block of code a specific number of times. However, when you need to execute a loop for each iteration of another loop, nested loops come into play.

Advantages and Disadvantages of Nested Loops

Nested loops are advantageous when working with multi-dimensional arrays or complex operations. However, they can be computationally expensive and affect the efficiency of the code, especially when dealing with large data sets.

Use Cases for Nested Loops

Nested loops are commonly used in sorting algorithms (like bubble sort), pattern generation, matrix operations, and graphical simulations.

III. Nested for Loops

Explanation of Nested for Loops

A nested for loop is essentially a for loop inside another for loop. The inner loop executes completely for each iteration of the outer loop.

Syntax for Nested for Loops

The syntax for a nested for loop in C is as follows:

for (initialization; condition; increment) {
    for (initialization; condition; increment) {
        // Inner loop statements
    }
    // Outer loop statements
}

Examples of Nested for Loops

The code below prints the pattern of an asterisk pyramid using a nested for loop:

#include<stdio.h>
int main() {
   int i, j, rows;
   printf("Enter the number of rows: ");
   scanf("%d", &rows);
   for(i=1; i<=rows; ++i) {
      for(j=1; j<=i; ++j) {
         printf("* ");
      }
      printf("\n");
   }
   return 0;
}

Here, the outer loop manages the number of rows, and the inner loop manages the number of asterisks per row.

IV. Nested while Loops

Explanation of Nested while Loops

A nested while loop involves a while loop inside another while loop. The inner while loop will execute all its iterations for each individual iteration of the outer loop.

Syntax for Nested while Loops

The syntax for a nested while loop in C is as follows:

while(condition) {
    while(condition) {
        // Inner loop statements
    }
    // Outer loop statements
}

Examples of Nested while Loops

Here's an example of a nested while loop in C which prints a simple 2D pattern:

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

This nested while loop works similarly to the for loop example, printing a 3x3 pattern.

V. Nested do-while Loops

Explanation of Nested do-while Loops

A nested do-while loop has a do-while loop inside another do-while loop. Unlike for and while loops, the inner loop will execute at least once, regardless of the condition, for each outer loop iteration.

Syntax for Nested do-while Loops

The syntax for a nested do-while loop is:

do {
    do {
        // Inner loop statements
    } while(condition);
    // Outer loop statements
} while(condition);

Examples of Nested do-while Loops

Here's an example of a nested do-while loop:

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

This example demonstrates the same 3x3 matrix pattern using a do-while loop instead.

VI. Best Practices

Nested loops can be a powerful tool in programming, but they need to be used with caution to ensure the efficiency and readability of your code. Here are some best practices for using nested loops in C:

1. Limit the Levels of Nesting

While nested loops are incredibly useful, excessive nesting can lead to difficult-to-understand and maintaining code. It's generally a good practice to limit the depth of nested loops to three levels. 

2. Understand Time Complexity

Nested loops can significantly impact the time complexity of your code. A single loop has a time complexity of O(n), but a nested loop has a time complexity of O(n^2). If you nest three loops, the time complexity becomes O(n^3), and so on. 

3. Avoid Unnecessary Computations Inside Loops

Performing unnecessary computations inside a loop can slow down your program, especially when dealing with nested loops. Wherever possible, perform computations outside the loop and use the result inside the loop.

4. Use Break and Continue Wisely

The break and continue statements can be useful in controlling the flow of your loops. Break allows you to exit the entire loop prematurely while continuing skips to the next iteration of the loop, bypassing the remaining code in the loop. 

5. Ensure Correct Initialisation and Update of Loop Variables

Ensure loop variables are correctly initialized before the loop and properly updated during each iteration. Failing to do so can lead to infinite loops or loops that don’t execute as expected.

6. Use Descriptive Variable Names

Especially with nested loops, using descriptive variable names can make your code much easier to understand. For example, if you're looping through a matrix, you might use row and col as loop variables rather than i and j.

7. Document Your Code

Use comments to document your code, especially when using nested loops. Explain what each loop is intended to do. This will make your code easier to understand.

Examples to Implement and Demonstrate the Use of Nested Loop in C

We’ve seen quite a few nested loop example in C so far in the article. Let’s now take it a notch further and look at some more, slightly complex examples and implementations of nested loop in C. 

Example 1: Generating a Multiplication Table

Nested loops can be used to generate a multiplication table, a classic example used in learning the basics of loops.

#include<stdio.h>
int main() {
   int l, m;
   for(l=1; l<=10; l++) {
      for(m=1; m<=10; m++) {
         printf("%d\t", l*m);
      }
      printf("\n");
   }
   return 0;
}

In this program, the outer loop runs from 1 to 10, representing the numbers for which we want to generate the multiplication table. The inner loop also runs from 1 to 10, and in each iteration, it multiplies the outer loop counter (m) with the inner loop counter (m), printing the result as a table.

Output:

12345678910
2468101214161820
36912151821242730
...
102030405060708090100

Example 2: Finding Prime Numbers

Nested loops can also be useful for checking prime numbers within a certain range.

#include<stdio.h>
int main() {
   int l, m, isPrime, n;
   printf("Enter the range of numbers to check for prime: ");
   scanf("%d", &n);
   for(l=2; l<=n; l++) {
      isPrime = 1;
      for(m=2; m<=l/2; m++) {
         if(l%m == 0) {
            isPrime = 0;
            break;
         }
      }
      if(isPrime)
         printf("%d ", l);
   }
   return 0;
}

In this program, the outer loop runs from 2 to n (input by the user). The inner loop checks for divisibility from 2 to l/2 (as a number is not divisible by numbers greater than its half), and if the number is divisible, it's not a prime number (isPrime = 0). If it isn't divisible by any number, it is a prime number and gets printed.

Output (For n = 10):

Enter the range of numbers to check for prime: 10
2 3 5 7

Example 3: Transposing a Matrix

Nested loops are commonly used to perform operations on matrices. Here's a nested loop example where we are transposing a matrix:

#include<stdio.h>
int main() {
   int l, m, matrix[3][3], transpose[3][3];
   printf("Enter elements of the matrix:\n");
   for(l=0; l<3; l++)
      for(m=0; m<3; m++) {
         printf("Enter element a%d%d: ",l+1,m+1);
         scanf("%d", &matrix[l][m]);
      }

   printf("\nOriginal matrix:\n");
   for(l=0; l<3; l++) {
      for(m=0; m<3; m++) {
         printf("%d\t",matrix[l][m]);
         if(m==2)
            printf("\n");
      }
   }

   for(l=0; l<3; l++)
      for(m=0; m<3; m++)
         transpose[m][l] = matrix[l][m];

   printf("\nTransposed matrix:\n");
   for(l=0; l<3; l++) {
      for(m=0; m<3; m++) {
         printf("%d\t",transpose[l][m]);
         if(m==2)
            printf("\n");
      }
   }
   return 0;
}

In this program, the outer loop iterates over rows and the inner loop iterates over columns. First, we input the elements of the matrix, then print it, then transpose it by swapping rows with columns, and finally print the transposed matrix.

Output:

Enter elements of the matrix:
Enter element a11: 1
Enter element a12: 2
Enter element a13: 3
Enter element a21: 4
Enter element a22: 5
Enter element a23: 6
Enter element a31: 7
Enter element a32: 8
Enter element a33: 9

Original matrix:
123
456
789

Transposed matrix:
147
258
369

Example 4: Printing a Diamond Pattern

Nested loops can be used to print interesting patterns. Let's print a diamond pattern:

#include<stdio.h>
int main() {
   int i, j, rows;
   printf("Enter number of rows: ");
   scanf("%d",&rows);
   for(i=1; i<=rows; i++) {
      for(j=1; j<=rows-i; j++)
         printf(" ");
      for(j=1; j<=2*i-1; j++)
         printf("*");
      printf("\n");
   }
   for(i=rows-1; i>=1; i--) {
      for(j=1; j<=rows-i; j++)
         printf(" ");
      for(j=1; j<=2*i-1; j++)
         printf("*");
      printf("\n");
   }
   return 0;
}

In this program, we print spaces and asterisks on each line to form a diamond shape. The first half of the diamond is formed by the first outer loop, and the second half is formed by the second outer loop.

Output (For rows = 5):

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Conclusion

Nested loop in C provides an efficient way to manage multi-dimensional data structures and perform repeated operations. They are powerful, and understanding them is crucial for anyone keen on mastering C programming.

However, nested loops require careful handling and optimisation to ensure they don't burden your program's efficiency. Understanding the various types of nested loops and when to use them will undoubtedly make your programming journey more comfortable.

Check out upGrad's DevOps Engineer Bootcamp to dive deeper into programming and master the world of loops, conditions, and functions.

FAQs

1. What is a nested loop in C?
A nested loop in C is a loop within another loop. For each iteration of the outer loop, the inner loop executes completely.

2. What are the types of nested loops in C?
The three main types of nested loops in C are: nested for loop, nested while loop, and nested do-while loop.

3. When should I use a nested loop in C?
Nested loop in C is often used when dealing with complex problems requiring multi-dimensional operations such as matrix manipulations, complex calculations, simulations, pattern printing, and sorting algorithms.

Leave a Reply

Your email address will not be published. Required fields are marked *