Nested loops in C involve placing one loop inside another loop. Each type of loop (for, while, or do-while) can be nested inside any other type. Nesting loops are useful for problems involving multi-dimensional data structures or complex iteration patterns.
A nested for loop means placing one for loop inside another for loop. Here's an example that prints a multiplication table up to a specified number of rows and columns:
#include <stdio.h>
int main() {
int rows, columns;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
// Nested for loop to generate a multiplication table
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
printf("%d\\t", i * j); //
Print product of i and j
}
printf("\\n"); // New line after each row
}
return 0;
}
Enter the number of rows: 3
Enter the number of columns: 3
1 2 3
2 4 6
3 6 9
A nested while loop means placing one while loop inside another while loop. Here's an example that prints a pattern of numbers:
#include <stdio.h>
int main() {
int rows, columns;
int number = 1;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
// Nested while loop to print a pattern of numbers
int i = 1;
while (i <= rows) {
int j = 1;
while (j <= columns) {
printf("%d\\t", number);
number++;
j++;
}
printf("\\n"); // New line after each row
i++;
}
return 0;
}
Enter the number of rows: 3
Enter the number of columns: 5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
A nested do-while loop means placing one do-while loop inside another do-while loop. Here's an example that prints a pattern of asterisks (*):
#include <stdio.h>
int main() {
int i, j;
// Outer loop for rows
do {
// Inner loop for columns
j = 1; // Initialize inner loop variable
do {
printf("%d\\t", j); // Print
the number
j++; // Increment inner loop
variable
} while (j <= 10); // Condition for inner
loop
printf("\\n"); // Move to the next line after inner
loop finishes
i++; // Increment outer loop variable
} while (i <= 10); // Condition for outer loop
return 0;
}
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
• Complexity: The complexity increases with nested loops. Be mindful of performance and ensure that the loop conditions are set correctly to avoid infinite loops.
• Initialization: Properly initialize loop variables and ensure they are updated within the loop to avoid unexpected behavior.
• Output: Carefully consider the output format and spacing, especially when dealing with nested loops.