Control Flow
Control flow refers to the order in which statements are executed in a program. Conditional statements allow the program to execute a specific block of code only if a given condition is true.
1. The if Statement
The if statement is the most basic control flow structure. The code inside the curly braces ({}) executes only if the expression inside the parentheses (()) evaluates to true (any non-zero value).
Syntax:
if (condition) {
// Code to execute if the condition is TRUE
}
Example
int score = 85;
if (score > 80) {
printf("Excellent score!\n");
}
2. The if...else Statement
The if...else structure provides an alternative path for execution when the initial condition is false.
Syntax:
if (condition) {
// Code to execute if the condition is TRUE
} else {
// Code to execute if the condition is FALSE
}
Example
int age = 17;
if (age >= 18) {
printf("You are eligible to vote.\n");
} else {
printf("You are not yet eligible to vote.\n");
}
3. The if...else if...else Chain
The else if statement allows you to test multiple conditions sequentially. Execution stops as soon as the first true condition is found, and only the code block associated with that condition is executed. If no conditions are true, the final else block (if present) is executed.
Syntax:
if (condition1) {
// Code for condition 1
} else if (condition2) {
// Code for condition 2
} else {
// Code if ALL conditions above are FALSE
}
Example (Grading System)
int grade = 75;
if (grade >= 90) {
printf("Grade: A\n");
} else if (grade >= 80) {
printf("Grade: B\n");
} else if (grade >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: Below C\n");
}
4. Nested if Statements
You can place if or if...else structures inside another if or else block. This is called nesting and is used to handle multiple layers of dependencies.
Example
int is_logged_in = 1; // 1 for true, 0 for false
int has_premium = 0;
if (is_logged_in == 1) {
printf("User is authenticated.\n");
if (has_premium == 1) {
printf("Accessing premium content.\n");
} else {
printf("Accessing standard content.\n");
}
} else {
printf("Please log in to continue.\n");
}
5. Single Statement Blocks
If an if, else if, or else structure controls only a single statement, the curly braces ({}) are optional, though generally recommended for clarity and preventing bugs.
int x = 10;
if (x > 5)
printf("X is large.\n"); // Only this line is conditional
else
printf("X is small.\n"); // Only this line is conditional
