📚 Chapter 3 🟢 Beginner → Intermediate ⏱ 60 min

Control Statements
& Program Flow

Give your programs the power of decision — if, else, switch, and loops. The building blocks that transform a linear list of instructions into intelligent, responsive software.

🎯 Learning Objectives
Use if, if-else, and nested if
Build else-if ladders for multiple choices
Use switch for fixed-value dispatch
Write while, do-while, and for loops
Apply break, continue, and goto correctly
Choose the right loop for any situation
1Foundations

Introduction to Control Statements

Real programs don’t simply march through instructions in a straight line. They face questions and must respond to data dynamically. Is the student’s mark above 50? Is the button currently pressed? Has the sensor exceeded 60 ’C? Depending on the answer, completely different code should run.

This ability to make decisions and repeat actions is what separates a program from a calculator. Control statements give a C program its intelligence.

👥

Student passed?

If marks ≥ 35, print “Pass”. Otherwise print “Fail”. One condition, two outcomes.

🎈

ATM PIN correct?

Only allow withdrawal if PIN matches. Nested decisions: correct PIN → sufficient balance → dispense cash.

🌡

Temperature > 60 ’C?

Turn the cooling fan ON. Otherwise keep it OFF. A real embedded system decision loop.

🔌

Print 1 – 100

Instead of 100 printf calls, a single loop runs the same line 100 times automatically.

💡
The Core Idea
Without control statements, every instruction would execute every time the program runs. Decision statements select which code runs; loop statements control how many times it runs.
2Foundations

Why Control Statements Exist

Think of a traffic signal. It doesn’t open the road permanently — it makes a decision on every cycle:

🟢 Green
if(light == GREEN) allow_traffic(); /* go */
🔴 Red
else stop_traffic(); /* stop */

Programs model exactly this logic. Without control statements, you could only write programs that do the same fixed thing every time — no user input, no sensors, no conditions, no loops. That covers almost nothing useful.

Real-World Decision Examples

SituationConditionTrue actionFalse action
ATM machinePIN correct?Allow withdrawalShow error
Online paymentPayment successful?Place orderCancel order
Embedded fanTemperature > 60’C?Turn fan ONKeep fan OFF
Login systemUsername & password match?Grant accessReject login
Sensor alarmPressure > threshold?Trigger alarmNormal operation
3Foundations

Classification of Control Statements

C’s control statements fall into three families. This chapter covers them all.

Control Statements in C — three families Decision Making 4. – 8. Looping 9. – 13. Jump Statements 14. – 16. if if…else else-if switch while do-while for break continue goto All three families work together. Decisions select paths; loops repeat them; jumps redirect control flow.

Three families of C control statements — all covered in this chapter

4Decision Making

The if Statement

The if statement is the most fundamental control statement. It executes a block of code only when a condition evaluates to true. If the condition is false, the block is skipped entirely.

C — if syntax
if(condition)
{
    /* Runs only when condition is true (non-zero) */
    statements;
}
START condition true / false true if block executes false (skip) Continue program execution

The if block only runs when the condition is true. False skips it and program continues normally.

Examples

C — Three if examples
#include <stdio.h>

int main()
{
    int age = 20;
    if(age >= 18)
    {
        printf("Eligible to Vote\n");    /* condition is true */
    }

    int marks = 90;
    if(marks >= 35)
    {
        printf("Pass\n");                /* condition is true */
    }

    int number = 12;
    if(number % 2 == 0)
    {
        printf("Even Number\n");         /* condition is true */
    }

    return 0;
}
Output
Eligible to Vote Pass Even Number
💡
True in C = Any Non-Zero Value
In C, 0 means false and any non-zero value means true. So if(100) executes the block (100 is non-zero = true). This is important: it means a non-NULL pointer is “true”, a non-zero sensor reading is “true”, etc.
5Decision Making

if…else Statement

When there are exactly two possible outcomes, use if  else. Exactly one of the two blocks will execute — never both, never neither.

C — if-else syntax
if(condition)
{
    /* Runs when condition is TRUE */
}
else
{
    /* Runs when condition is FALSE */
}
START condition ? true if block executes false else block executes Continue

Exactly one branch always executes. The two paths merge and continue together after the if-else.

C — if-else examples
/* Voting eligibility */
int age = 15;
if(age >= 18)    printf("Adult\n");
else             printf("Minor\n");      /* Minor */

/* Even or odd */
int number = 7;
if(number % 2 == 0)    printf("Even\n");
else                   printf("Odd\n");  /* Odd */

/* Embedded: fan control */
int temperature = 45;
if(temperature > 40)    printf("Fan ON\n");   /* Fan ON */
else                    printf("Fan OFF\n");
6Decision Making

Nested if

A nested if is an if statement placed inside another if block. It is used when a second condition only makes sense to check after the first condition is true.

C — Nested if syntax
if(condition1)
{
    /* outer condition is true */
    if(condition2)
    {
        /* both conditions are true */
        statements;
    }
}
C — Login system example
#include <stdio.h>

int main()
{
    int age     = 25;
    int citizen = 1;   /* 1 = yes, 0 = no */

    if(age >= 18)
    {
        /* outer: old enough? */
        if(citizen)
        {
            /* inner: is a citizen? */
            printf("Eligible to Vote\n");
        }
        else
        {
            printf("Not a citizen\n");
        }
    }
    else
    {
        printf("Too young to vote\n");
    }

    return 0;
}
Output (age=25, citizen=1)
Eligible to Vote
⚠️
Keep Nesting Shallow
More than 2–3 levels of nested if makes code very hard to read. When you find yourself with deeply nested conditions, consider using logical operators (&&, ||) to combine them, or restructure with early returns.
7Decision Making

else-if Ladder

When there are more than two mutually exclusive outcomes, use an else-if ladder. The conditions are tested top-to-bottom; the first matching block executes, and all others are skipped.

C — else-if ladder syntax
if(condition1)       { /* first choice  */ }
else if(condition2)  { /* second choice */ }
else if(condition3)  { /* third choice  */ }
else                 { /* fallback      */ }
C — Grade calculator
#include <stdio.h>

int main()
{
    int marks = 82;

    if(marks >= 90)
        printf("Grade A\n");
    else if(marks >= 75)
        printf("Grade B\n");   /* This executes: 82 >= 75 */
    else if(marks >= 50)
        printf("Grade C\n");
    else
        printf("Fail\n");

    return 0;
}
Output
Grade B

Why else-if Is Better Than Separate ifs

✗ Separate ifs — both may print (x=60)
if(x > 50) printf("A"); /* executes */ if(x > 40) printf("B"); /* also executes! */ /* Output: AB — wrong */
✓ else-if — only first match runs
if(x > 50) printf("A"); /* executes */ else if(x > 40) printf("B"); /* skipped */ /* Output: A — correct */
8Decision Making

switch Statement

The switch statement is the ideal tool when you need to select one option from a fixed set of integer or character values. It is cleaner and often faster than a long else-if ladder for menu-driven programs.

C — switch syntax
switch(expression)
{
    case constant1:
        statements;
        break;        /* ESSENTIAL: exits the switch */

    case constant2:
        statements;
        break;

    default:
        statements;   /* runs if no case matches */
}

How switch Executes

1
Evaluate the expression
The expression must produce an integer or character value (e.g. int day = 3;).
2
Compare with each case constant
The compiler jumps directly to the matching case label. If no case matches, it jumps to default.
3
Execute statements until break
Execution runs from the matching case downward until a break is encountered or the closing brace.
4
break exits the switch
Control jumps to the statement after the closing } of the switch block.
C — Day name example
#include <stdio.h>

int main()
{
    int day = 3;

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

    return 0;
}
Output
Wednesday

Fall-Through: What Happens Without break

✗ Without break (choice=2) case 2: print "Two" falls through! case 3: print "Three" falls through! default Output: TwoThree + default! ✓ With break (choice=2) case 2: print "Two" break; jumps out of switch Output: Two ✓

Without break, execution falls through into subsequent cases. Always add break unless you intend fall-through.

switch vs else-if Ladder

Aspectswitchelse-if ladder
Works withInteger & char constantsAny expression
Works with floats/strings?NoYes
Readability (many choices)BetterVerbose
PerformanceOften faster (jump table)Sequential tests
Best forMenus, fixed optionsRanges, complex logic
9Loops

Why Loops? Overview

Loops solve the problem of repetition. Without them, printing “Hello” 100 times would require 100 separate printf calls. With a loop, it’s three lines.

✗ Without loops (verbose & unscalable)
printf("Hello\n"); printf("Hello\n"); printf("Hello\n"); /* ... 97 more lines ... */
✓ With a loop (clean & scalable)
for(int i = 0; i < 100; i++) printf("Hello\n");

The Three Loop Types

LoopWhen to useCondition checkedMin. executions
forKnown number of iterationsBefore each iteration0 (can skip entirely)
whileUnknown iterations, condition-drivenBefore each iteration0 (can skip entirely)
do-whileMust run at least once (e.g. menu)After each iteration1 (always)
🔌
Loops in Embedded Systems
The most important loop in embedded systems is the super loop: an infinite while(1) or for(;;) in main() that continuously reads sensors, processes data, and updates outputs. It never exits — that’s by design.
10Loops

while Loop

The while loop keeps executing its body as long as the condition remains true. The condition is checked before each iteration, so if it is false from the start, the body never runs.

C — while syntax
while(condition)
{
    /* body: runs while condition is true */
    /* MUST update something to avoid infinite loop */
}
C — Print 1 to 5
#include <stdio.h>

int main()
{
    int i = 1;              /* initialization */

    while(i <= 5)          /* condition */
    {
        printf("%d\n", i);  /* body */
        i++;                /* update — ESSENTIAL! */
    }

    return 0;
}
Output
1 2 3 4 5

Infinite while Loop (Embedded Super Loop)

C — Classic embedded main loop
int main()
{
    /* Initialization — runs once */
    init_hardware();
    init_sensors();

    /* Super loop — runs forever */
    while(1)
    {
        read_sensors();
        process_data();
        update_display();
        control_actuators();
    }

    /* Never reached */
    return 0;
}
🔌
The Embedded Super Loop
while(1) is the heartbeat of virtually every embedded program. A microcontroller never “finishes” its task — it continuously monitors inputs and drives outputs until power is removed or a reset occurs.
Most Common while Mistake
Forgetting to update the loop variable: while(i <= 5) { printf("%d", i); } — without i++, i stays at 1 forever, printing 1 endlessly. Always ensure something in the body moves the condition toward false.
11Loops

do…while Loop

The do while loop is unique: it executes its body first, then checks the condition. This guarantees the body runs at least once, regardless of the initial condition value.

C — do-while syntax
do
{
    /* body always executes at least once */
    statements;
}
while(condition);   /* ← semicolon required here! */
C — Print 1 to 5
int i = 1;

do
{
    printf("%d\n", i);
    i++;
}
while(i <= 5);
Output
1 2 3 4 5

The Key Difference: while vs do-while

while (condition false from start)
int i = 10; while(i < 5) { printf("Hello\n"); /* never runs */ } /* Output: (nothing) */
do-while (runs at least once)
int i = 10; do { printf("Hello\n"); /* runs once */ } while(i < 5); /* Output: Hello */

Best Use Case: Input Validation Menu

C — Menu that always shows at least once
int choice;

do
{
    printf("1. Add\n2. Subtract\n3. Exit\n");
    printf("Enter choice: ");
    scanf("%d", &choice);
}
while(choice != 3);     /* keep showing menu until user picks 3 */
💡
When to Use do-while
Use do-while for menus, input validation loops, and any situation where the body must execute before you can even know whether to continue. If you can know before entering whether to run at all, use while instead.
12Loops

for Loop

The for loop is the most commonly used loop in C. It bundles initialization, condition, and update into a single line, making it ideal when the number of iterations is known in advance.

C — for syntax with annotations
/*        init    condition    update  */
for(int i = 1;   i <= 5;      i++   )
{
    /* body: runs 5 times */
}
① Initialization i = 1 (runs once) ② Condition i <= 5 ? false Exit Loop true ③ Body printf("%d\n", i) ④ Update: i++ → back to ② loops back

The for loop cycle: init → check condition → body → update → check condition → ... until false

C — for loop examples
/* 1. Print 1 to 5 */
for(int i = 1; i <= 5; i++)
    printf("%d ", i);         /* 1 2 3 4 5 */

/* 2. Print squares */
for(int i = 1; i <= 5; i++)
    printf("%d ", i * i);     /* 1 4 9 16 25 */

/* 3. Count down */
for(int i = 10; i >= 1; i--)
    printf("%d ", i);         /* 10 9 8 ... 1 */

/* 4. Infinite for loop (equivalent to while(1)) */
for(;;)
{
    /* runs forever */
}

while vs for — Same Result, Different Style

while (control spread out)
int i = 1; /* init */ while(i <= 5) /* condition */ { printf("%d\n", i); i++; /* update */ }
for (control in one place)
for(int i=1; i<=5; i++) { printf("%d\n", i); } /* init, cond, update all on one line */
13Loops

Nested Loops

A nested loop is a loop placed inside another loop. For every one iteration of the outer loop, the inner loop runs completely from start to finish.

C — Nested loop with coordinate pairs
for(int i = 1; i <= 3; i++)          /* outer: 3 iterations */
{
    for(int j = 1; j <= 2; j++)      /* inner: 2 iterations each */
    {
        printf("(%d,%d) ", i, j);
    }
    printf("\n");
}
Output — inner loop runs 6 times total (3 × 2)
(1,1) (1,2) (2,1) (2,2) (3,1) (3,2)

Pattern Programs with Nested Loops

Rectangle pattern (4×4)
for(int i=1; i<=4; i++) { for(int j=1; j<=4; j++) printf("* "); printf("\n"); }
Triangle pattern
for(int i=1; i<=5; i++) { for(int j=1; j<=i; j++) printf("* "); printf("\n"); }
Rectangle output
* * * * * * * * * * * * * * * *
Triangle output
* * * * * * * * * * * * * * *
14Jump Statements

break Statement

The break statement immediately terminates the nearest enclosing loop or switch. Execution jumps to the first statement after the closing brace of that loop or switch.

C — break example
#include <stdio.h>

int main()
{
    for(int i = 1; i <= 10; i++)
    {
        if(i == 5)
            break;           /* exit loop when i reaches 5 */

        printf("%d ", i);
    }

    printf("\n(loop ended early)\n");

    return 0;
}
Output
1 2 3 4 (loop ended early)

break in while and do-while

C — Search and stop early
int arr[] = {10, 30, 50, 70, 90};
int target = 50;
int found = 0;

for(int i = 0; i < 5; i++)
{
    if(arr[i] == target)
    {
        found = 1;
        printf("Found at index %d\n", i);
        break;          /* no need to keep searching */
    }
}

if(!found)
    printf("Not found\n");
💡
break Only Exits One Level
In nested loops, break exits only the innermost loop containing it. To break out of multiple loops, use a flag variable, goto (one of the few valid uses), or restructure as a function.
15Jump Statements

continue Statement

continue skips the rest of the current iteration and jumps directly to the next iteration’s condition check. Unlike break, the loop itself does not terminate.

C — Skip number 3
#include <stdio.h>

int main()
{
    for(int i = 1; i <= 5; i++)
    {
        if(i == 3)
            continue;      /* skip when i is 3 */

        printf("%d ", i);
    }

    return 0;
}
Output (3 is missing)
1 2 4 5

break vs continue — Visual Comparison

break iter 1 iter 2 break! exits loop after loop Iterations 3, 4, 5 never run Loop terminates completely continue iter 1 iter 2 continue! skip rest, next iter 4 iter 5 Iteration 3 body skipped Loop continues normally

break kills the loop; continue just skips the remainder of the current iteration and loops again

Aspectbreakcontinue
EffectExits the loop entirelySkips current iteration only
Loop continues?No — terminatesYes — at next iteration
Common useSearch and early exitSkip specific values
16Jump Statements

goto Statement

The goto statement transfers control unconditionally to a labeled statement in the same function. It is the most powerful (and most dangerous) jump statement.

C — goto syntax and example
#include <stdio.h>

int main()
{
    goto end;           /* jump — skips printf below */

    printf("Hello");   /* NEVER executes */

end:                    /* label: any identifier followed by : */
    printf("World\n"); /* executes */

    return 0;
}
Output
World
⚠️
Why goto Is Discouraged (“Spaghetti Code”)
Unrestricted goto creates “spaghetti code” — programs where control jumps unpredictably, making it impossible to trace what has happened when reaching any given point. For 99% of cases, break, continue, return, and functions are better alternatives.

When goto Is Acceptable

C — Valid use: exiting multiple nested loops
for(int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; j++)
    {
        for(int k = 0; k < 10; k++)
        {
            if(arr[i][j][k] == target)
                goto found;    /* break only exits innermost */
        }
    }
}

printf("Not found\n");
goto done;

found:
    printf("Found!\n");

done:
    ;    /* empty statement after final label */
17Jump Statements

Loop Selection Guide

SituationBest LoopReason
Known count (print 1–10)forInit, condition, update all in one line
Condition depends on runtime datawhileClean when update happens inside body
Must run at least once (menu)do-whileBody executes before first condition check
Read until valid inputdo-whileAlways prompt at least once
Embedded super loopwhile(1)Intent is immediately clear
Process all array elementsforIndex counter maps naturally to for

Complete Loop Comparison Table

Featurewhiledo-whilefor
Condition checked first?YesNoYes
Executes at least once?NoYesNo
Init/update in syntax?NoNoYes
Best for known count?FairPoorExcellent
Needs semicolon after condition?NoYesNo
18Practical Programs

Practical Programs

Sum of First N Numbers

C — Sum 1 to 10
#include <stdio.h>

int main()
{
    int sum = 0;

    for(int i = 1; i <= 10; i++)
        sum += i;        /* sum = sum + i */

    printf("Sum = %d\n", sum);   /* Sum = 55 */

    return 0;
}
Output
Sum = 55

Factorial of a Number

C — 5! = 120
#include <stdio.h>

int main()
{
    int fact = 1;

    for(int i = 1; i <= 5; i++)
        fact *= i;       /* 1×2×3×4×5 */

    printf("5! = %d\n", fact);   /* 5! = 120 */

    return 0;
}

Multiplication Table

C — Table of 7
#include <stdio.h>

int main()
{
    int n = 7;

    for(int i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);

    return 0;
}
Output (first 4 lines)
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 ... 7 x 10 = 70

Reverse a Number

C — Reverse 12345 → 54321
#include <stdio.h>

int main()
{
    int num = 12345, reversed = 0;

    while(num != 0)
    {
        int digit = num % 10;    /* extract last digit */
        reversed  = reversed * 10 + digit;
        num      /= 10;          /* remove last digit  */
    }

    printf("Reversed: %d\n", reversed);   /* 54321 */

    return 0;
}

Basic Calculator with switch

C — Menu-driven calculator
#include <stdio.h>

int main()
{
    float a, b;
    int op;

    printf("Enter two numbers: ");
    scanf("%f %f", &a, &b);

    printf("1.Add  2.Sub  3.Mul  4.Div\n");
    printf("Enter choice: ");
    scanf("%d", &op);

    switch(op)
    {
        case 1: printf("%.2f\n", a + b); break;
        case 2: printf("%.2f\n", a - b); break;
        case 3: printf("%.2f\n", a * b); break;
        case 4:
            if(b != 0)  printf("%.4f\n", a / b);
            else        printf("Division by zero!\n");
            break;
        default: printf("Invalid choice\n");
    }

    return 0;
}

Triangle Pattern

C — Right-aligned triangle of numbers
for(int i = 1; i <= 5; i++)
{
    for(int j = 1; j <= i; j++)
        printf("%d ", j);

    printf("\n");
}
Output
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Check Prime Number

C — Is n prime?
#include <stdio.h>

int main()
{
    int n = 17, is_prime = 1;

    if(n < 2)
    {
        is_prime = 0;
    }
    else
    {
        for(int i = 2; i * i <= n; i++)
        {
            if(n % i == 0)
            {
                is_prime = 0;
                break;
            }
        }
    }

    printf("%d is %s\n", n, is_prime ? "Prime" : "Not Prime");

    return 0;
}
Output
17 is Prime

Fibonacci Series

C — First 10 Fibonacci numbers
#include <stdio.h>

int main()
{
    int a = 0, b = 1, c, n = 10;

    printf("%d %d ", a, b);

    for(int i = 2; i < n; i++)
    {
        c = a + b;
        printf("%d ", c);
        a = b;
        b = c;
    }
    printf("\n");

    return 0;
}
Output
0 1 1 2 3 5 8 13 21 34
19Review

Common Mistakes

Mistake 1 — Semicolon after if

✗ Empty if body — block always executes
if(x > 5); /* ← semicolon = empty if body */ { printf("Hello"); /* ALWAYS prints — not conditional */ }
✓ No semicolon
if(x > 5) { printf("Hello"); /* only prints when x > 5 */ }

Mistake 2 — Assignment instead of comparison

✗ = assigns (always true if value is non-zero)
if(x = 5) /* assigns 5 to x, condition = 5 = true */ printf("yes");
✓ == compares
if(x == 5) /* tests whether x equals 5 */ printf("yes");

Mistake 3 — Missing braces (dangling else)

✗ Only first statement is in the if
if(x > 5) printf("A\n"); printf("B\n"); /* ALWAYS prints — not in if block */
✓ Braces make scope clear
if(x > 5) { printf("A\n"); printf("B\n"); /* only prints when x > 5 */ }

Mistake 4 — Missing break in switch

✗ Falls through all cases
switch(x) { case 1: printf("One"); /* no break! */ case 2: printf("Two"); /* no break! */ case 3: printf("Three"); } /* If x=1: prints OneTwoThree */
✓ break terminates each case
switch(x) { case 1: printf("One"); break; case 2: printf("Two"); break; case 3: printf("Three"); break; } /* If x=1: prints One only */

Mistake 5 — Forgetting the loop update (infinite loop)

✗ i never changes — runs forever
int i = 1; while(i <= 5) { printf("%d\n", i); /* forgot i++ */ }
✓ i increments each iteration
int i = 1; while(i <= 5) { printf("%d\n", i); i++; /* moves toward false */ }

Mistake 6 — Semicolon after while

✗ while loops forever on nothing
while(i < 5); /* loops forever — empty body */ { printf("Hello"); /* only runs AFTER the while exits */ }
✓ No semicolon after while condition
while(i < 5) /* no semicolon */ { printf("Hello"); i++; }
20Review

Best Practices

Always use braces

Even for single-statement if/else/loops. Braces prevent the dangling-else bug and make adding more statements safe later.

Always add break in switch

Unless fall-through is specifically intended and clearly commented. Accidental fall-through is one of the most confusing C bugs.

Choose for when count is known

If you know you need exactly N iterations, for keeps init, condition, and update together in one readable line.

Initialise loop variables

Never rely on an uninitialized variable as a loop counter. Set it to a known value immediately before or in the for header.

Use parentheses for clarity

Write if((a > 10) && (b < 20)) rather than if(a>10&&b<20). Parentheses cost nothing and save confusion.

Keep nesting shallow

Beyond 3 levels of nested if or loops, readability degrades sharply. Refactor into functions or use early return/break.

Prefer while(1) over for(;;)

For embedded super loops, while(1) makes the intent immediately obvious to beginners. Both compile identically.

Avoid goto (almost always)

Use functions, structured loops, break, and return instead. Reserve goto for the rare multi-level loop escape and error cleanup patterns.

21Review

Memory Tricks

I S N E
Iif
Sswitch
Nnested
Eelse-if

“I Switch N Else” — the four decision-making tools

StatementThink of it as…When to use
ifOne door: open or skipSingle condition, one possible action
if  elseFork in the road: left or rightTwo mutually exclusive outcomes
nested ifGate inside a gateSecondary condition depends on first
else-ifStaircase of choicesMultiple mutually exclusive ranges/values
switchTV remote: press one buttonFixed set of integer/char values
whileKeep walking while path is clearUnknown iteration count
do-whileTake one step, then checkMust execute at least once
forCountdown timerKnown iteration count
breakEmergency exitStop loop/switch immediately
continueSkip this floor, go to nextSkip one iteration, keep looping
22Review

Interview Questions

Q1
What is the difference between if and if-else?
if executes a block only when the condition is true. If false, nothing happens. if-else executes one of exactly two blocks: the if block when true, the else block when false. With if alone, the false case simply produces no action.
Q2
What is fall-through in switch and how do you prevent it?
Fall-through is when execution continues into the next case after a matching case finishes, because no break was present. To prevent it, add break; at the end of every case block. Intentional fall-through is occasionally useful (e.g. two cases sharing the same action) but should be clearly commented.
Q3
What is the difference between while and do-while?
  • while: checks the condition before the first iteration. If false from the start, the body never executes (0 times).
  • do-while: executes the body first, then checks the condition. The body always runs at least once, regardless of the initial condition.
Q4
What is the difference between break and continue?
  • break: exits the loop (or switch) entirely. The code after the closing brace executes next.
  • continue: skips only the remainder of the current iteration and jumps to the next iteration’s condition check. The loop itself keeps running.
Q5
Why is while(1) common in embedded systems?
Embedded microcontrollers run continuously until powered off or reset. There is no “end of program” like a desktop app. The while(1) super loop models this: it continuously reads sensors, processes data, and drives outputs forever. Exiting main() has no well-defined behavior on most bare-metal targets.
Q6
When should you use switch instead of else-if?
Use switch when selecting among a fixed set of integer or character constants (e.g. a menu, day-of-week, state machine states). Use else-if when comparing ranges, using floating-point values, testing strings, or when conditions involve complex expressions. switch often compiles to a jump table, which is faster than a sequence of comparisons.
Q7
What value represents false in C? What is true?
0 is false. Any non-zero integer value is true — this includes negative numbers, large positive numbers, and non-NULL pointers. There is no dedicated boolean type in C89/C90, but C99 added _Bool and <stdbool.h> which provides bool, true (= 1), and false (= 0).
Q8
Why is goto discouraged? When is it acceptable?
Unrestricted goto creates “spaghetti code” — control flow that jumps unpredictably, making the program state at any point hard to reason about. Acceptable uses: (1) breaking out of multiple nested loops when the code would be clearer than a flag variable, (2) error-cleanup code in system-level C (the Linux kernel uses it for this). Always limit jumps to a clearly labeled exit point within the same function.

Frequently Asked Questions

Can I use switch with strings in C?
No. C’s switch only works with integer and character types. Strings (which are char arrays) cannot be used as switch expressions because they are compared by pointer address, not by content. Use if(strcmp(str, "value") == 0) from <string.h> for string comparison.
Is an else block always required with if?
No. The else block is entirely optional. A standalone if simply does nothing when the condition is false. Add else only when you need a specific action for the false case. Similarly, a default in switch is optional but recommended as a safety net for unexpected values.
What happens if break is missing from the last case in switch?
Nothing harmful — after the last case (or default) executes, the switch’s closing } is reached and execution continues naturally after the switch block. Adding a break to the last case is still good practice for consistency and makes it easy to safely reorder cases later without introducing accidental fall-through.
23Review

Practice Programs

🟢 Easy — Decision Making
  • Check whether a number entered by the user is positive, negative, or zero.
  • Check whether a number is even or odd using if-else.
  • Find the largest of two numbers using if-else.
  • Build a simple day-name printer: user enters 1–7, program prints Monday–Sunday using switch.
  • Check voting eligibility: user enters age, program prints “Eligible” or “Not eligible”.
🔵 Medium — Loops
  • Print all even numbers from 2 to 50 using a for loop.
  • Print all numbers from 1 to 100 that are divisible by 3 using a while loop.
  • Build a basic calculator using switch inside a do-while loop that repeats until the user chooses Exit.
  • Print the multiplication table of any number entered by the user.
  • Calculate the sum of digits of a number (e.g. 1234 → 1+2+3+4 = 10) using while.
🔴 Challenge
  • Write a program to determine whether a year is a leap year (hint: use nested if for the three conditions).
  • Print the Fibonacci series up to N terms using a for loop.
  • Write a program to find all prime numbers between 2 and 100 (use a nested for loop with break).
  • Print the following number triangle using nested loops:

    1
    12
    123
    1234
    12345
  • Check if a number is a palindrome (same forwards and backwards, e.g. 121). Use while loop to extract digits, then compare.
24Review

Chapter Summary

✅ What you mastered in Chapter 3
  • Control statements give programs the ability to make decisions and repeat actions.
  • if executes a block only when a condition is true. 0 is false; any non-zero is true.
  • if-else selects exactly one of two blocks based on a condition.
  • Nested if places a decision inside another decision for multi-level conditions.
  • The else-if ladder tests multiple mutually exclusive conditions; only the first match executes.
  • switch dispatches to a matching case label. Always use break to prevent fall-through.
  • while checks its condition before each iteration; runs 0 or more times.
  • do-while checks its condition after the body; always runs at least once.
  • for bundles init, condition, and update in one line; best when count is known.
  • Nested loops: for every outer iteration, the inner loop runs completely.
  • break exits the nearest loop or switch immediately.
  • continue skips the rest of the current iteration and proceeds to the next.
  • goto is valid but almost always replaceable with better structured code.
  • Avoid semicolons after if and while conditions — they create empty bodies.
  • The embedded super loop (while(1)) is the heartbeat of every microcontroller program.
📚 Chapter 4 — Functions, Arrays & Strings
Organizing code into reusable blocks and working with collections of data
What is a Function?
Function Declaration
Return Values
Parameters & Arguments
Call by Value
Scope of Variables
Recursion
Arrays
Strings & String Functions
Practice Programs
Interview Questions