Control Flow Statements in C
If-Else Statements
The if statement is used to execute a block of code if a specified condition is true. The else statement can be used to execute a block of code if the condition is false.
int a = 10;
if (a > 5) {
printf("a is greater than 5\n");
} else {
printf("a is not greater than 5\n");
}
Switch Statement
The switch statement is used to execute one block of code among many, based on the value of a variable.
int day = 3;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
default:
printf("Other day\n");
}
Loops
Loops are used to execute a block of code repeatedly. C provides three types of loops:
For Loop
The for loop is used when the number of iterations is known.
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
While Loop
The while loop is used when the number of iterations is not known, and it continues until a condition is false.
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
Do-While Loop
The do-while loop is similar to the while loop but guarantees that the block of code is executed at least once.
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
Break and Continue Statements
The break statement is used to exit from a loop or switch statement, while the continue statement is used to skip the current iteration and proceed to the next iteration of the loop.
Example of break:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
printf("%d\n", i);
}
Example of continue:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
printf("%d\n", i);
}
Nested Loops and Conditional Statements
Loops and conditional statements can be nested within each other to perform complex tasks.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
if (i == j) {
printf("i equals j when i=%d and j=%d\n", i, j);
} else {
printf("i does not equal j when i=%d and j=%d\n", i, j);
}
}
}
Summary
Understanding control flow statements is essential for programming in C. This post covered if-else statements, switch statements, loops, break and continue statements, and nested loops and conditional statements.
For more detailed information, you can refer to the following resources:


0 Comments: