GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

🚦 Lesson 5: Control Flow (Decision Making)

⏱️ Estimated time: 25 minutes | Difficulty: Beginner

Logic Power

Control flow allows your program to make decisions and execute different code based on conditions.

If / Else Statements

#include <stdio.h>

int main() {
    int age = 18;

    if (age >= 18) {
        printf("You are an adult\n");
    } else if (age >= 13) {
        printf("You are a teenager\n");
    } else {
        printf("You are a child\n");
    }

    // Ternary operator (shorthand if/else)
    int x = 10;
    char *result = (x > 5) ? "Big" : "Small";
    printf("%s\n", result);  // Big

    return 0;
}

Switch Statement

int day = 3;
switch (day) {
    case 1: printf("Monday\n"); break;
    case 2: printf("Tuesday\n"); break;
    case 3: printf("Wednesday\n"); break;
    case 4: printf("Thursday\n"); break;
    case 5: printf("Friday\n"); break;
    default: printf("Weekend\n");
}

⚠️ Don't forget break;! Without it, execution "falls through" to the next case.

For Loop

// Print 0 to 4
for (int i = 0; i < 5; i++) {
    printf("%d ", i);  // 0 1 2 3 4
}

// Countdown
for (int i = 10; i > 0; i--) {
    printf("%d...", i);
}
printf("Liftoff!\n");

While Loop

int count = 0;
while (count < 3) {
    printf("Count: %d\n", count);
    count++;
}

// Do-While (executes at least once)
int num;
do {
    printf("Enter a positive number: ");
    scanf("%d", &num);
} while (num <= 0);

Break & Continue

// break: exit the loop
for (int i = 0; i < 10; i++) {
    if (i == 5) break;    // Stop at 5
    printf("%d ", i);      // 0 1 2 3 4
}

// continue: skip current iteration
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue;  // Skip even numbers
    printf("%d ", i);            // 1 3 5 7 9
}

✅ Quick Quiz

❓ What happens without break in a switch case?

❓ How many times does: for(int i=0; i<3; i++) run?

❓ What does 'continue' do in a loop?

← Previous Next: Functions →