Control flow statements in C allow us to control the flow of execution of a program. They determine which statements should be executed based on certain conditions. There are three primary types of control flow statements in C:
The if statement allows you to execute a block of code based on a condition. If the condition evaluates to true, the block of code will execute. The else statement allows you to execute an alternative block if the condition is false.
if (condition) { // Block of code executed if condition is true } else { // Block of code executed if condition is false }
#includeint main() { int age = 20; if (age >= 18) { printf("You are eligible to vote.\n"); } else { printf("You are not eligible to vote.\n"); } return 0; }
The switch statement evaluates an expression and executes the corresponding case based on the value of the expression. If no cases match, the default case is executed (if present).
switch (expression) { case value1: // Block of code executed for value1 break; case value2: // Block of code executed for value2 break; default: // Block of code executed if no case matches }
#includeint main() { 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("Invalid day\n"); } return 0; }
Loops allow you to repeat a block of code multiple times. There are three main types of loops in C:
#includeint main() { for (int i = 1; i <= 5; i++) { printf("%d\n", i); } return 0; }
#includeint main() { int i = 1; while (i <= 5) { printf("%d\n", i); i++; } return 0; }
#includeint main() { int i = 1; do { printf("%d\n", i); i++; } while (i <= 5); return 0; }
break
and continue
incorrectly inside loops.break
statement in a switch
case, causing the code to "fall through" to the next case.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!