Control Flow in C
Master decision-making and loops: if-else, switch-case, for, while, do-while. Learn how programs make choices and repeat actions.
๐ฏ What is Control Flow?
By default, C programs execute statements sequentially (line by line). But real-world programs need to make decisions and repeat actions. Control flow statements let you:
๐ก Three Types of Control Flow
- Sequential - Execute one after another (default)
- Conditional - Execute only if a condition is true (if-else, switch)
- Iterative - Repeat multiple times (loops: for, while, do-while)
๐ If-Else Statements
The if statement is like asking a yes/no question. If the answer is "yes" (true), execute some code. If "no" (false), skip it or do something else.
๐ค How If-Else Works (Real-world Analogy)
Imagine a traffic light:
- if (light is green) โ Go
- else if (light is yellow) โ Slow down
- else (light is red) โ Stop
1. Simple If Statement
Use when you want to do something only if a condition is true.
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
// Simple if - executes only if condition is true
if (age >= 18) {
printf("You are an adult!\n");
}
// This always executes (not inside if)
printf("Thanks for using our program.\n");
return 0;
}
๐ Execution Flow
- Program asks for age
- Checks: Is age >= 18?
- If YES โ Print "You are an adult!"
- If NO โ Skip the if block entirely
- Print "Thanks for using our program." (always runs)
2. If-Else Statement
Use when you have two choices: do this OR do that.
#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
// Check if number is even or odd
if (num % 2 == 0) {
// This block runs if remainder is 0 (even)
printf("%d is EVEN\n", num);
} else {
// This block runs if condition is false (odd)
printf("%d is ODD\n", num);
}
return 0;
}
๐งฎ Understanding the Condition: num % 2 == 0
%is the modulo operator (gives remainder)num % 2gives the remainder when divided by 2- Even numbers รท 2 have remainder 0
- Odd numbers รท 2 have remainder 1
==checks if two values are equal
3. If-Else If-Else Ladder
Use when you have multiple conditions to check in order.
#include <stdio.h>
int main() {
int score;
printf("Enter your score (0-100): ");
scanf("%d", &score);
// Multiple conditions checked in order
if (score >= 90) {
printf("Grade: A (Excellent!)\n");
} else if (score >= 80) {
printf("Grade: B (Good job!)\n");
} else if (score >= 70) {
printf("Grade: C (Average)\n");
} else if (score >= 60) {
printf("Grade: D (Needs improvement)\n");
} else {
printf("Grade: F (Failed)\n");
}
return 0;
}
๐ How the Ladder Works
- Check: score >= 90? If yes โ Grade A, STOP
- If no, check: score >= 80? If yes โ Grade B, STOP
- If no, check: score >= 70? If yes โ Grade C, STOP
- If no, check: score >= 60? If yes โ Grade D, STOP
- If none above โ else block runs โ Grade F
Important: Only ONE block runs! Once a condition is true, the rest are skipped.
4. Nested If Statements
An if statement inside another if statement.
#include <stdio.h>
int main() {
int age;
char hasLicense;
printf("Enter your age: ");
scanf("%d", &age);
printf("Do you have a license? (y/n): ");
scanf(" %c", &hasLicense); // Space before %c skips whitespace
// Outer if
if (age >= 18) {
printf("You are old enough to drive.\n");
// Inner if - only checks if outer is true
if (hasLicense == 'y' || hasLicense == 'Y') {
printf("And you have a license! You can drive.\n");
} else {
printf("But you need a license to drive.\n");
}
} else {
printf("You are too young to drive.\n");
}
return 0;
}
5. Ternary Operator (Shorthand If-Else)
A compact way to write simple if-else: condition ? value_if_true : value_if_false
#include <stdio.h>
int main() {
int a = 10, b = 20;
// Long way with if-else
int max;
if (a > b) {
max = a;
} else {
max = b;
}
// Short way with ternary operator
int max2 = (a > b) ? a : b;
// Can also use directly in printf
printf("Maximum is: %d\n", (a > b) ? a : b);
// Check even/odd
int num = 15;
printf("%d is %s\n", num, (num % 2 == 0) ? "even" : "odd");
return 0;
}
๐๏ธ Switch Statement
Use switch when you need to compare one variable against multiple constant values. It's cleaner than a long if-else ladder.
๐ค When to Use Switch vs If-Else
| Use Switch When... | Use If-Else When... |
|---|---|
| Checking one variable against exact values | Checking ranges (age > 18) |
| Values are integers or characters | Conditions are complex |
| Code readability matters | Need floating-point checks |
1. Basic Switch Syntax
#include <stdio.h>
int main() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1:
printf("Sunday\n");
break; // Exit switch after this case
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid day! Please enter 1-7.\n");
}
return 0;
}
๐ How Switch Works
- Evaluate the expression in
switch(expression) - Jump to the
casethat matches the value - Execute statements from that case onward
breakexits the switch statement- If no case matches,
defaultruns (if present)
โ ๏ธ The "Fall-Through" Behavior
Without break, execution continues to the NEXT case! This is called "fall-through".
switch(grade) {
case 'A':
printf("Excellent! ");
// No break! Falls through to B
case 'B':
printf("Good job! ");
// No break! Falls through to C
case 'C':
printf("Passed.\n");
break; // Now stops
}
Output for grade 'A': "Excellent! Good job! Passed."
Lesson: Always use break unless you intentionally want fall-through!
2. Calculator Using Switch
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator); // Space before %c
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(operator) {
case '+':
result = num1 + num2;
printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error: Cannot divide by zero!\n");
}
break;
default:
printf("Invalid operator! Use +, -, *, or /\n");
}
return 0;
}
๐ก Key Points
switchworks withint,char, andenumtypescasevalues must be constants (not variables)- Multiple cases can share the same code:
switch(grade) {
case 'A':
case 'a':
printf("Excellent!\n");
break;
case 'B':
case 'b':
printf("Good!\n");
break;
}
๐ Loops in C
Loops let you execute code multiple times without writing it repeatedly. Imagine printing numbers 1 to 1000 - loops make this easy!
๐ข For Loop
Best when you know how many times to repeat (counting)
โฑ๏ธ While Loop
Best when you don't know the count, but know when to stop
โ Do-While Loop
Best when you need to run at least once
1. For Loop
Structure: for(initialize; condition; update)
๐ For Loop Flow
- Initialize: Set starting value (runs once)
- Condition: Check if we should continue
- Execute: Run the loop body
- Update: Change the counter
- Repeat: Go back to step 2
#include <stdio.h>
int main() {
// Example 1: Print 1 to 5
printf("Counting 1 to 5:\n");
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n\n");
// Example 2: Count backwards
printf("Counting 5 to 1:\n");
for (int i = 5; i >= 1; i--) {
printf("%d ", i);
}
printf("\n\n");
// Example 3: Sum of first 10 numbers
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum = sum + i; // or sum += i
}
printf("Sum of 1 to 10 = %d\n\n", sum);
// Example 4: Multiplication table
int num = 7;
printf("Multiplication table of %d:\n", num);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
๐ Dry Run: Sum of 1 to 10
| Iteration | i value | sum before | sum after (sum += i) | Condition |
|---|---|---|---|---|
| 1 | 1 | 0 | 1 | 1<=10 โ |
| 2 | 2 | 1 | 3 | 2<=10 โ |
| 3 | 3 | 3 | 6 | 3<=10 โ |
| ... | ... | ... | ... | ... |
| 10 | 10 | 45 | 55 | 10<=10 โ |
| End | 11 | 55 | - | 11<=10 โ |
Final result: sum = 55
2. While Loop
Checks condition first, then executes. Might run zero times!
#include <stdio.h>
int main() {
// Example 1: Basic counting
int i = 1; // Initialize before loop
while (i <= 5) { // Check condition
printf("%d ", i);
i++; // Update inside loop
}
printf("\n\n");
// Example 2: Count digits in a number
int num, count = 0;
printf("Enter a number: ");
scanf("%d", &num);
int temp = num;
while (temp != 0) {
temp = temp / 10; // Remove last digit
count++; // Count one digit
}
printf("Number of digits in %d = %d\n\n", num, count);
// Example 3: Reverse a number
temp = num;
int reversed = 0;
while (temp != 0) {
int digit = temp % 10; // Get last digit
reversed = reversed * 10 + digit; // Append to result
temp = temp / 10; // Remove last digit
}
printf("Reversed: %d\n", reversed);
return 0;
}
๐ Reverse Number Example: Step by Step
For input 1234:
| Step | temp | digit (temp%10) | reversed (reversed*10+digit) |
|---|---|---|---|
| Start | 1234 | - | 0 |
| 1 | 123 | 4 | 0*10+4 = 4 |
| 2 | 12 | 3 | 4*10+3 = 43 |
| 3 | 1 | 2 | 43*10+2 = 432 |
| 4 | 0 | 1 | 432*10+1 = 4321 |
3. Do-While Loop
Executes first, then checks. Always runs at least once!
#include <stdio.h>
int main() {
// Menu-driven program (classic do-while use case)
int choice;
do {
printf("\n===== MENU =====\n");
printf("1. Print Hello\n");
printf("2. Print Current Date\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Hello, World!\n");
break;
case 2:
printf("Today's date: April 18, 2026\n");
break;
case 3:
printf("Goodbye!\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 3); // Continue until user chooses 3
printf("Program ended.\n");
return 0;
}
๐ For vs While vs Do-While Comparison
| Feature | For Loop | While Loop | Do-While |
|---|---|---|---|
| When to use | Known iterations | Unknown iterations | At least once |
| Condition check | Before execution | Before execution | After execution |
| Minimum runs | 0 times | 0 times | 1 time |
4. Nested Loops
A loop inside another loop. Useful for patterns and 2D structures.
#include <stdio.h>
int main() {
// Pattern: Right triangle
printf("Right Triangle Pattern:\n");
for (int i = 1; i <= 5; i++) { // Outer loop: rows
for (int j = 1; j <= i; j++) { // Inner loop: columns
printf("* ");
}
printf("\n"); // New line after each row
}
// Output:
// *
// * *
// * * *
// * * * *
// * * * * *
printf("\nMultiplication Table (1-5):\n");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%4d", i * j); // %4d for alignment
}
printf("\n");
}
return 0;
}
๐ Control Statements: break & continue
โน๏ธ break
Immediately exit the loop/switch. Jump to the next statement after the loop.
โญ๏ธ continue
Skip the rest of current iteration. Jump to the next iteration.
#include <stdio.h>
int main() {
// break example: Find first number divisible by 7
printf("First number > 50 divisible by 7: ");
for (int i = 51; i <= 100; i++) {
if (i % 7 == 0) {
printf("%d\n", i);
break; // Exit loop immediately
}
}
// continue example: Print only odd numbers
printf("Odd numbers from 1 to 10: ");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i); // Only runs for odd numbers
}
printf("\n");
// Real-world: Skip invalid inputs
printf("\nProcessing valid scores only:\n");
int scores[] = {85, -5, 92, 101, 78, -10, 95};
int size = 7;
for (int i = 0; i < size; i++) {
if (scores[i] < 0 || scores[i] > 100) {
printf("Skipping invalid score: %d\n", scores[i]);
continue;
}
printf("Processing score: %d\n", scores[i]);
}
return 0;
}
๐ Visual Comparison
Normal Loop Flow: With break: With continue:
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ Start โ โ Start โ โ Start โ
โโโโโโโโฌโโโโโโโ โโโโโโโโฌโโโโโโโ โโโโโโโโฌโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโ
โ Condition? โ โ Condition? โ โ Condition? โ
โโโโโโโโฌโโโโโโโ โโโโโโโโฌโโโโโโโ โโโโโโโโฌโโโโโโโ
Yes/No Yes/No Yes/No
โ โ โ โ โ โ
Yes No Yes No Yes No
โ โ โ โ โ โ
โผ โผ โผ โผ โผ โผ
โโโโโโโโโโโ โโโโโโ โโโโโโโโโโโ โโโโโโ โโโโโโโโโโโ โโโโโโ
โ Body โโโโEnd โ โ Body โโโโEnd โ โ Body โโโโEnd โ
โโโโโโฌโโโโโ โโโโโโ โโโโโโฌโโโโโ โโโโโโ โโโโโโฌโโโโโ โโโโโโ
โ โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
break โโโโโโโโโโโโโโโโโโโโโ
(jump to End)
continue
(jump to Condition) โโโโโโ
๐ Summary
| Statement | Use When... | Syntax |
|---|---|---|
if |
One condition, one action | if (cond) { ... } |
if-else |
Two mutually exclusive actions | if (cond) { ... } else { ... } |
if-else if |
Multiple conditions to check | if (c1) {...} else if (c2) {...} |
switch |
Variable matches constants | switch(v) { case 1: ... } |
for |
Known iteration count | for (i=0; i<n; i++) { ... } |
while |
Unknown count, condition-based | while (cond) { ... } |
do-while |
Must run at least once | do { ... } while (cond); |