Nested Loops and Conditions
You can place one loop or condition inside another to solve more complex problems (like patterns or matrix operations).
- Nested for Loop Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
printf(“i=%d j=%d\n”, i, j);
}
}
Output:
i=1 j=1
i=1 j=2
i=2 j=1
i=2 j=2
i=3 j=1
i=3 j=2
Nested if Statement Example:
int age = 20;
int hasID = 1;
if (age >= 18) {
if (hasID == 1) {
printf(“You can vote.”);
} else {
printf(“ID required.”);
}
} else {
printf(“Not eligible to vote.”);
}
Tip: Indentation and proper use of {} braces are very important in nested structures to maintain code clarity and avoid logical errors.