Published: 24 Apr 2025 | Reading Time: 7 min read
Have you ever wondered how to efficiently process multidimensional data like tables, matrices, or grids in C? One effective way to handle multidimensional data is with nested loops. A nested loop in C refers to a loop running inside another loop, making it a powerful tool for handling repetitive tasks within a structured sequence. When working on pattern printing, matrix operations, or sophisticated data processing, nested loops can help reduce your code and increase productivity.
In this article, we'll go over nested loops, their various types (for, while, and do-while loops), as well as guide you through practical examples with detailed descriptions and outputs. Continue reading to learn about nested loops in C and elevate your programming skills.
A nested loop in C is a loop within another loop. This structure allows the inner loop to run fully each time the outer loop iterates. This indicates that the number of times the inner loop repeats its operation is determined by the outer loop. When working with multi-dimensional data, such as arrays or matrices, where you must handle data in both rows and columns, these are very useful.
Outer loop
{
Inner loop
{
………
………
}
………
}
In C programming, a nested loop can be created using different loop structures. The three main types of nested loops are:
Each of these functions has different purposes depending on the problem you're trying to solve.
The nested for loop in C is the most commonly used type of nested loop when working with multi-dimensional arrays, creating number patterns, or handling matrix operations. This loop allows you to control both the outer and inner iterations.
for (int i = 0; i < outer_limit; i++) { // Outer loop
for (int j = 0; j < inner_limit; j++) { // Inner loop
// Statements
}
}
This program demonstrates how the C nested for loop works:
#include <stdio.h>
int main() {
int c, d;
printf("Nested For Loop Example:\n");
for (c = 1; c <= 4; c++) {
for (d = 1; d <= 4; d++) {
printf("c: %d, d: %d\n", c, d);
}
printf("End of Inner Loop\n");
}
return 0;
}
This C program demonstrates how nested for loops work. The outer loop runs with variable c from 1 to 4, and for each c, the inner loop runs with d from 1 to 4. During each inner loop cycle, it prints the values of c and d. Once the inner loop finishes for a particular c, it displays "End of Inner Loop" to mark its completion.
Nested For Loop Example:
c: 1, d: 1
c: 1, d: 2
c: 1, d: 3
c: 1, d: 4
End of Inner Loop
c: 2, d: 1
c: 2, d: 2
c: 2, d: 3
c: 2, d: 4
End of Inner Loop
c: 3, d: 1
c: 3, d: 2
c: 3, d: 3
c: 3, d: 4
End of Inner Loop
c: 4, d: 1
c: 4, d: 2
c: 4, d: 3
c: 4, d: 4
End of Inner Loop
A nested while loop is similar to a nested for loop, but the syntax of a nested while loop is distinct from a for loop, although similar in principle. In a nested while loop, one while loop is placed inside another loop so that before the outer loop goes to the next iteration, the complete inner loop has executed throughout the outer loop. This way, one can carry out a set of instructions, the same instruction, multiple times, that is based on another repetitive operation.
while (condition) { // Outer loop
while (condition) { // Inner loop
// Statements
}
// Statements
}
The following program makes you understand how the nested while loop in C works:
#include <stdio.h>
int main() {
int c = 1, d;
printf("Nested While Loop Example:\n");
while (c <= 3) { // Outer loop
d = 1;
while (d <= 3) { // Inner loop
printf("c: %d, d: %d\n", c, d);
d++;
}
printf("End of Inner Loop\n");
c++;
}
return 0;
}
In this program, the outer while loop runs from c = 1 to c = 3. For each iteration of the outer loop, the inner while loop runs from d = 1 to d = 3. During each iteration of the inner loop, the current values of i and j are printed, which shows the current combination of these values. After the inner loop completes, a message "End of Inner Loop" is printed, and the outer loop moves to the next iteration.
Nested While Loop Example:
c: 1, d: 1
c: 1, d: 2
c: 1, d: 3
End of Inner Loop
c: 2, d: 1
c: 2, d: 2
c: 2, d: 3
End of Inner Loop
c: 3, d: 1
c: 3, d: 2
c: 3, d: 3
End of Inner Loop
A nested do-while loop is a structure where a do-while loop is placed inside another do-while loop. The essential feature of the do-while loop is that it always executes the code block at least once. This behaviour applies to the outer and inner loops in a nested structure, which ensures that sets of statements run at least once, even if the conditions are false from the start.
do {
// Outer loop statements
do {
// Inner loop statements
} while (inner_condition); // Condition for the inner loop
} while (outer_condition); // Condition for the outer loop
This C program explains the operation of a nested do-while loop.
#include <stdio.h>
int main() {
int x = 1, y;
printf("Nested Do-While Loop Example:\n");
do { // Outer do-while loop
y = 1;
do { // Inner do-while loop
printf("x: %d, y: %d\n", x, y);
y++;
} while (y <= 4); // Inner loop condition
printf("End of Inner Loop\n");
x++;
} while (x <= 4); // Outer loop condition
return 0;
}
Nested Do-While Loop Example:
x: 1, y: 1
x: 1, y: 2
x: 1, y: 3
x: 1, y: 4
End of Inner Loop
x: 2, y: 1
x: 2, y: 2
x: 2, y: 3
x: 2, y: 4
End of Inner Loop
x: 3, y: 1
x: 3, y: 2
x: 3, y: 3
x: 3, y: 4
End of Inner Loop
x: 4, y: 1
x: 4, y: 2
x: 4, y: 3
x: 4, y: 4
End of Inner Loop
Loops of any kind can nest inside loops of any kind. For example, you can place a while loop inside a for loop or a do-while loop inside another while loop. This flexibility allows developers to handle complex iteration scenarios in C programming.
Here are a few examples of how different types of loops can be nested within each other in C:
In this example, the inner while loop prints asterisks in each row, while the outer for loop determines the number of rows.
#include <stdio.h>
int main() {
int p, q;
for (p = 1; p <= 3; p++) {
q = 1;
while (q <= i) {
printf("* ");
q++;
}
printf("\n");
}
return 0;
}
The outer for loop controls the number of rows and runs from p = 1 to p = 3. Inside it, the while loop is supposed to print stars in each row. However, there is a mistake in the code: it uses i instead of p. If corrected to while (q <= p), the program would print a right-angled triangle of stars, increasing one star per row.
*
* *
* * *
This example uses a do-while loop nestled inside a for loop to check and report prime values from 2 to 20.
#include <stdio.h>
int main() {
int p, q, isPrime;
for (p = 2; p <= 20; p++) {
q = 2;
isPrime = 1;
do {
if (p % q == 0) {
isPrime = 0;
break;
}
q++;
} while (q <= p / 2);
if (isPrime)
printf("%d ", p);
}
return 0;
}
This C program prints all prime numbers between 2 and 20. It uses a for loop to check each number p from 2 to 20. For each number, it assumes isPrime is true (set to 1). Then, using a do-while loop, it checks if p is divisible by any number q from 2 to p/2. If it finds a divisor, it sets isPrime to 0 and stops checking further. After verification, the integer is reported as a prime number if isPrime is still 1.
2 3 5 7 11 13 17 19
This example prints a pattern with numbers from 1 to the current row number in each row by nesting a for loop inside a while loop.
#include <stdio.h>
int main() {
int p = 1, q;
while (p <= 3) {
for (q = 1; q <= p; q++) {
printf("%d ", q);
}
printf("\n");
p++;
}
return 0;
}
This C program prints a simple number pattern using a while loop and a for loop. The variable p starts at 1 and goes up to 3, controlling the number of rows. For each value of p, the for loop prints numbers from 1 to p. After printing the numbers in a row, it moves to the next line.
1
1 2
1 2 3
The two statements break and continue helps to control the flow of execution in the nested loops.
break: Immediately exits the nearest enclosing loop (inner or outer, depending on where it's placed). It's useful when a condition is met and you no longer need to continue the current loop.
continue: It moves straight on to the next iteration of the closest loop, skipping the statements that remain in the current loop cycle.
These break and continue statements in C help make your nested loops more efficient and readable by allowing early exits or skipping specific iterations.
The advantage and disadvantages of nested loops in C are as follows:
Nested loops in C are used in programming for a combination of tasks. Here are some standard methods where they come in handy:
Nested loops access elements in two-dimensional arrays (or arrays with more dimensions). For example, when dealing with a grid of data, the outer loop handles rows, and the inner loop processes the columns within each row.
They are also helpful in developing patterns or shapes in text-based applications, like drawing triangles, squares, or other shapes in the console. Each loop helps create different levels or rows of the shape.
When performing calculations on matrices, such as adding or multiplying matrices, nested loops allow you to systematically go through each element in a matrix. This is essential for operations that involve rows and columns interacting with each other.
In problems that involve finding combinations or permutations, nested loops help by iterating through different sets of items or sequences to create all possible combinations.
When using nested loop in C programming, it's important to follow some best practices to confirm your code is efficient and easy to maintain.
Try to avoid using too many levels of nested loops. Too many nested loops can make your code harder to understand and maintain. Refactor your code to reduce the number of loops.
Nested loops can slow down your program when working with large datasets. Be mindful of how the loops interact and try to reduce the number of iterations. Optimizing your loops can help improve the program's performance.
Choosing clear, explanatory variable names for your loop counters and other variables helps make the code more readable. This is important for future maintenance or when others are checking your code.
Use the break and continue statements to manage control flow within nested loops. These can help exit loops early or skip iterations when certain conditions are met, making the code more efficient.
If you have calculations inside the inner loop that don't change, move them outside the loop. Precomputing values before entering the loop can save processing time and improve efficiency.
A nested loop in C is a powerful tool for managing complex tasks that involve repetitive actions or multiple iterations. Programmers can easily tackle problems dealing with multidimensional data by learning how to use different types of loops, like nested for and while loops. Developers who follow best practices can write clear, efficient code that takes full advantage of nested loops.
A nested loop in C is when one loop is placed inside another, which allows the inner loop to run multiple times for each iteration of the outer loop. For complicated tasks and multidimensional data, this is helpful.
The main types of nested loops in C are the for, while, and do-while loops. Each type can be nested, depending on the needs of the iteration.
Yes! Printing a multiplication table can be done with a nested for loop. For example, one loop runs through the rows, and the other runs through the columns to display results like i×j.
Nested loops are helpful when working with multidimensional data, like matrices, or when you need to perform repeated tasks that involve multiple layers of iteration, such as generating patterns.
Pitfalls include too many nested loops making the code complex and harder to read, as well as performance issues due to higher time complexity. Optimizing loops and maintaining a manageable nesting depth are crucial.
You can use the break statement to exit a nested loop. You need to use flags or other control structures to exit both loops.
Yes, you can nest different types of loops, like placing a for loop inside a while loop or vice versa. This allows for more flexibility in your iteration patterns.
About NxtWave
NxtWave is a learning platform offering comprehensive programming courses and resources. For more information, visit www.ccbp.in or contact [email protected].
Contact Information: