Control Flow & Decision Making
By default, code executes sequentially from top to bottom. Control flow statements allow the program to take branches and make decisions based on conditions.
1. The If-Else Statement
The if statement evaluates a condition. In C, any non-zero value is treated as true, and zero is treated as false:
#include <stdio.h>
int main() {
int temperature = 28;
if (temperature > 30) {
printf("It's hot outside.\n");
} else if (temperature >= 15) {
printf("The weather is pleasant.\n");
} else {
printf("It's cold outside.\n");
}
return 0;
}
[!WARNING] In C, if you omit curly braces
{}for aniforelseblock, only the single immediate statement following it is considered part of the conditional. It is a highly recommended convention to always use curly braces to avoid structural errors.
2. The Switch-Case Statement
The switch statement selects one of many code blocks to execute based on the value of a single variable. The variable must be an integer type (int or char):
#include <stdio.h>
int main() {
char operator = '+';
int a = 10, b = 5;
switch (operator) {
case '+':
printf("Sum: %d\n", a + b);
break; // Exits switch block
case '-':
printf("Difference: %d\n", a - b);
break;
default:
printf("Unknown operator\n");
}
return 0;
}
Guide: If you omit the break; statement at the end of a case, execution will "fall through" into the next case, executing its statements as well. This is sometimes intentional but usually a bug.
3. The Ternary Operator
The ternary operator (? :) is a shorthand conditional expression:
// condition ? expression_if_true : expression_if_false
int age = 19;
char* status = (age >= 18) ? "Adult" : "Minor";