Nested loops and decision statements
Nested loops and decision statements are powerful constructs in C programming that allow you to combine loop structures and decision-making to solve complex problems. They provide a way to control the flow of execution based on multiple conditions and perform repetitive tasks within each iteration.
Nested Loops:
Nested loops refer to having one loop inside another. This allows you to create more complex loop structures to handle multidimensional data structures or perform iterations within iterations.
Here's an example of nested loops:
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d %d\n", i, j);
}
}
return 0;
}
In this example, the outer `for` loop runs three times, and for each iteration of the outer loop, the inner `for` loop runs three times. This results in a total of nine iterations. The program prints the values of `i` and `j` for each iteration, producing the following output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
The nested loops can be used to iterate through two-dimensional arrays, traverse tree structures, or solve problems that involve multidimensional data.
Nested Decision Statements:
Nested decision statements refer to having one decision statement (such as `if` or `switch`) inside another decision statement. This allows you to create more complex decision-making structures based on multiple conditions.
Here's an example of nested `if` statements:
#include <stdio.h>
int main() {
int num = 15;
if (num > 10) {
printf("Number is greater than 10.\n");
if (num > 20) {
printf("Number is also greater than 20.\n");
} else {
printf("Number is not greater than 20.\n");
}
} else {
printf("Number is not greater than 10.\n");
}
return 0;
}
In this example, the program first checks if `num` is greater than 10. If the condition is true, it enters the outer `if` block and prints "Number is greater than 10." Within the outer `if` block, it further checks if `num` is greater than 20. Depending on the result, it prints the corresponding message. If the initial condition is false, it enters the `else` block and prints "Number is not greater than 10."
Nested decision statements can be used to handle complex branching logic, implement cascading conditions, or solve problems that involve multiple levels of decision-making.
By combining nested loops and decision statements, you can create powerful algorithms to handle intricate data structures, perform complex computations, or solve intricate problems in your C programs.