Here’s an example of nested loops and complex control flow in C. This code generates a multiplication table for numbers from 1 to 5 and includes an example of using break and continue to manage control flow.
#include <stdio.h>
int main() {
int i, j;
printf("Multiplication Table (1 to 5):\n");
// Outer loop to iterate through rows (multipliers)
for (i = 1; i <= 5; i++) {
// Inner loop to iterate through columns (multiplicands)
for (j = 1; j <= 5; j++) {
// Example of control flow using "continue" and "break"
if (j == 3) {
continue; // Skip when j is 3, so 3 times any number isn't shown
}
if (i == 4) {
break; // Exit inner loop if i is 4, so row 4 is incomplete
}
printf("%d x %d = %2d\t", i, j, i * j);
}
printf("\n");
}
return 0;
} Explanation of Nested Loops and Complex Control Flow
1. Nested Loops
- Outer Loop (
forloop with variablei): Controls the rows in the table. It iterates from1to5, representing the multiplier. - Inner Loop (
forloop with variablej): Controls the columns in each row. It iterates from1to5, representing the multiplicand for each multiplier in the outer loop. - Output: The combination of the two loops generates pairs
(i, j)to compute the producti * j, and the results are displayed in a tabular format.
2. Control Flow Statements
continue: The continue statement in the inner loop skips the current iteration whenj == 3. This prevents printing any products wherej = 3(i.e.,i * 3values). Effect: The program skips calculations for3in each row, leaving the output without columns for3.
break: The break statement in the inner loop stops the inner loop immediately wheni == 4. Effect: The row corresponding toi = 4will not have anyprintfstatements, will print empty spaces.
Output of the Program
The output will look something like this, illustrating the skipped and broken values:
Multiplication Table (1 to 5): 1 x 1 = 1 1 x 2 = 2 1 x 4 = 4 1 x 5 = 5 2 x 1 = 2 2 x 2 = 4 2 x 4 = 8 2 x 5 = 10 3 x 1 = 3 3 x 2 = 6 3 x 4 = 12 3 x 5 = 15 5 x 1 = 5 5 x 2 = 10 5 x 4 = 20 5 x 5 = 25
Summary of Nested Loops and Complex Control Flow
- Nested Loops: Used here to create a multiplication table by combining
iandj. continueStatement: Skips an iteration within a loop, selectively omitting results when certain conditions are met.breakStatement: Exits the loop when a condition is met, as seen withi == 4to terminate the row early.
This example demonstrates how nested loops and control flow statements like break and continue can create complex behavior in structured, repeatable operations.
