SyntaxPilot
Courses/C Programming/Lesson 5

C Programming · Lesson 5 of 30 · 18 min

if / else and switch

queued

These are the notes for C episode 5. Until now every program ran every line, top to bottom. Here our programs learn to decide: run some lines only when a condition is true, pick one of several paths, and jump straight to the right option in a menu. You will learn if, else, the else if ladder, the ternary operator ? :, and switch with case, break and default, plus the traps that compile with no warning at all. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run with the input shown.

The problem: two messages, every time

In episode 4, a customer typed the bill in words (two fifty) and scanf told us it read 0 values. So the program knows the input is bad, but it carried on and printed "Each pays: 0". The obvious fix: add a warning line.

#include <stdio.h>

int main() {
    int bill = 0;
    printf("Enter the bill: ");
    int got = scanf("%d", &bill);
    printf("Please type a number!\n");
    printf("Each pays: %d\n", bill / 4);
    return 0;
}

Input two fifty:

Enter the bill: Please type a number!
Each pays: 0

Input 340:

Enter the bill: Please type a number!
Each pays: 85

Both messages, every single time, even when the input was fine.

Why? A program is a straight road: C runs line 1, then line 2, then line 3, every line, every time. We know the warning is "only for bad input", but nothing in the code says so. We need a fork in the road: check something first, then take one path or the other.

The fix: if

Think of a railway junction: one track splits into two, and the train takes only one. Which one? The signal answers a yes/no question. In C the question goes in brackets after if:

if (got == 0)
    printf("Please type a number!\n");

If the condition is true, the line under it runs. If it is false, C skips it.

#include <stdio.h>

int main() {
    int bill = 0;
    printf("Enter the bill: ");
    int got = scanf("%d", &bill);
    if (got == 0)
        printf("Please type a number!\n");
    printf("Each pays: %d\n", bill / 4);
    return 0;
}
Input Output
340 Enter the bill: Each pays: 85
two fifty Enter the bill: Please type a number! then Each pays: 0

Half fixed. Without braces, an if controls only the one statement right after it. The last printf is back on the main road, so it always runs.

else: the other path

We want exactly one of the two: bad input → only the warning; good input → only the split. In English: if the input is bad, warn, otherwise split. "Otherwise" in C is else. Curly braces { } group as many lines as you like into one path (a block).

#include <stdio.h>

int main() {
    int bill = 0;
    printf("Enter the bill: ");
    int got = scanf("%d", &bill);
    if (got == 0) {
        printf("Please type a number!\n");
    } else {
        printf("Each pays: %d\n", bill / 4);
    }
    return 0;
}
Input Output
two fifty Enter the bill: Please type a number!
340 Enter the bill: Each pays: 85

The rules of if / else

if (condition) {
    // runs when the condition is true
} else {
    // runs when the condition is false
}
  • The condition is just a number. 0 means false; any other number (1, 5, -3...) means true. Comparisons like got == 0 give 1 or 0 (episode 3).
  • else is optional and has no condition of its own: it means "in every other case".
  • Always use braces, even for one line. The traps below show why.

Three silent traps

A cinema gives a senior discount at age 60 and above. All three programs below compile with no error and no warning with the stage's command, and all three are wrong.

Trap 1: = instead of ==

#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    if (age = 60)
        printf("Senior discount!\n");
    printf("Age: %d\n", age);
    return 0;
}

Input 25:

Senior discount!
Age: 60

A single = assigns: it stores 60 in age, and the value of the whole expression is 60, which is not zero, so the if sees true. Use == to compare.

Trap 2: a semicolon after if ( )

#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    if (age >= 60);
        printf("Senior discount!\n");
    return 0;
}

Input 25:

Senior discount!

The ; is an empty statement. The if controls nothing, and the printf below is on the main road, so it always runs.

Trap 3: missing braces

#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    if (age >= 60)
        printf("Senior discount!\n");
        printf("Pay 120\n");
    return 0;
}

Input 25:

Pay 120

Without braces the if owns only the first line. Indentation means nothing to C: the second printf only looks like it belongs to the if.

Tip: compiling with gcc -Wall turns on extra warnings. With -Wall, gcc warns about all three: trap 1 gives "suggest parentheses around assignment used as truth value", and traps 2 and 3 give "this 'if' clause does not guard..." (misleading indentation). The SyntaxPilot compiler doesn't use -Wall, so build the habits: == to compare, no ; after the condition, always { }.

else if: the price ladder

The cinema has three prices: under 12 → ₹100, 12 to 59 → ₹200, 60 and above → ₹120. The obvious attempt is three separate ifs:

#include <stdio.h>

int main() {
    int age, price;
    scanf("%d", &age);
    if (age < 12) price = 100;
    if (age < 60) price = 200;
    if (age >= 60) price = 120;
    printf("Ticket: %d\n", price);
    return 0;
}

Input 8:

Ticket: 200

The child paid the adult price! Separate ifs are separate checks, and all of them run. 8 < 12 set the price to 100, but 8 is also < 60, so the second if overwrote it with 200.

Think of a queue with three counters. Counter 1 asks "under 12?"; if yes you pay and leave. Only if counter 1 said no do you walk to counter 2: that is else if. The last counter asks nothing; everyone who reaches it is a senior: the final else.

#include <stdio.h>

int main() {
    int age, price;
    scanf("%d", &age);
    if (age < 12)
        price = 100;
    else if (age < 60)
        price = 200;
    else
        price = 120;
    printf("Ticket: %d\n", price);
    return 0;
}
Input Output
8 Ticket: 100
30 Ticket: 200
65 Ticket: 120

The ladder stops at the first true condition, so order matters: if you checked age < 60 first, every child would land on 200.

The ternary operator ? :

When you just pick one of two values ("cold? chai, otherwise cold coffee"), C has a one-line shortcut:

condition ? value_if_true : value_if_false
#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    int price = (age >= 60) ? 120 : 200;
    printf("Ticket: %d\n", price);
    return 0;
}
Input Output
65 Ticket: 120
30 Ticket: 200

It is called ternary because it takes three parts. Use it for short either/or values; for anything longer, if / else is easier to read.

switch: menus

The chai stall menu: 1 Chai, 2 Coffee, 3 Lassi, 4 Samosa. With an else if ladder:

#include <stdio.h>

int main() {
    int choice;
    printf("1 Chai  2 Coffee  3 Lassi  4 Samosa: ");
    scanf("%d", &choice);
    if (choice == 1)
        printf("Chai: 15\n");
    else if (choice == 2)
        printf("Coffee: 25\n");
    else if (choice == 3)
        printf("Lassi: 40\n");
    else if (choice == 4)
        printf("Samosa: 20\n");
    else
        printf("Not on the menu\n");
    return 0;
}

Input 2 → 1 Chai 2 Coffee 3 Lassi 4 Samosa: Coffee: 25. It works, but choice == is repeated on every rung. With twenty items this is a mess.

Think of a customer-care phone menu: "press 1 for balance, 2 for recharge...". You press one key and it jumps straight to that option; after your answer you hang up; any other key gets "invalid option". That is switch:

Phone menu C
Press one key switch (choice) looks at one value
1 balance, 2 recharge... case 1: case 2: labels
Hang up after your answer break; leaves the switch
"Invalid option" default: catches everything else

Forget break: fall-through

#include <stdio.h>

int main() {
    int choice;
    printf("1 Chai  2 Coffee  3 Lassi  4 Samosa: ");
    scanf("%d", &choice);
    switch (choice) {
        case 1: printf("Chai: 15\n");
        case 2: printf("Coffee: 25\n");
        case 3: printf("Lassi: 40\n");
        case 4: printf("Samosa: 20\n");
        default: printf("Not on the menu\n");
    }
    return 0;
}

Input 2:

1 Chai  2 Coffee  3 Lassi  4 Samosa: Coffee: 25
Lassi: 40
Samosa: 20
Not on the menu

A case is only a label, an entry door, not a wall. switch jumps in at case 2: and keeps running every line below until it meets a break or the closing brace. This is called fall-through.

With break

#include <stdio.h>

int main() {
    int choice;
    printf("1 Chai  2 Coffee  3 Lassi  4 Samosa: ");
    scanf("%d", &choice);
    switch (choice) {
        case 1: printf("Chai: 15\n"); break;
        case 2: printf("Coffee: 25\n"); break;
        case 3: printf("Lassi: 40\n"); break;
        case 4: printf("Samosa: 20\n"); break;
        default: printf("Not on the menu\n");
    }
    return 0;
}
Input Output
2 1 Chai 2 Coffee 3 Lassi 4 Samosa: Coffee: 25
7 1 Chai 2 Coffee 3 Lassi 4 Samosa: Not on the menu

Fall-through on purpose: several labels, one answer

switch also works with characters (a char is a small whole number inside). To accept both m and M, stack the labels with no break between them:

#include <stdio.h>

int main() {
    char size;
    printf("Size (S/M/L): ");
    scanf(" %c", &size);
    switch (size) {
        case 's':
        case 'S': printf("Small: 10\n"); break;
        case 'm':
        case 'M': printf("Medium: 15\n"); break;
        case 'l':
        case 'L': printf("Large: 20\n"); break;
        default: printf("Unknown size\n");
    }
    return 0;
}
Input Output
m Size (S/M/L): Medium: 15
L Size (S/M/L): Large: 20

What switch can't do

#include <stdio.h>

int main() {
    float price = 1.5;
    switch (price) {
        case 1.5: printf("cheap\n"); break;
    }
    return 0;
}
main.c: In function 'main':
main.c:5:13: error: switch quantity not an integer
    5 |     switch (price) {
      |             ^~~~~
main.c:6:9: error: case label does not reduce to an integer constant
    6 |         case 1.5: printf("cheap\n"); break;
      |         ^~~~
#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    switch (age) {
        case age >= 60: printf("Senior\n"); break;
        default: printf("Not senior\n");
    }
    return 0;
}
main.c: In function 'main':
main.c:7:9: error: case label does not reduce to an integer constant
    7 |         case age >= 60: printf("Senior\n"); break;
      |         ^~~~

switch only works on integer types (int, char...). Each case label must be an integer constant: a fixed whole number or character known when the program is compiled. Not a decimal, not a variable, not a comparison.

if / else or switch?

Use if / else for Use switch for
Ranges: age < 12, marks >= 90 One int or char compared with fixed values
Decimals (float, double) Menus: 1, 2, 3... or 'S', 'M', 'L'
Several variables, && and || Several values sharing one answer (stacked labels)

Common mistakes (and the real gcc messages)

Mistake Code What gcc says / what happens
= instead of == if (age = 60) no error; every age passes and age becomes 60
; after the condition if (age >= 60); no error; the next line always runs
Missing braces two lines under an if, no { } no error; only the first line belongs to the if
Separate ifs for a ladder if (age < 12) ...; if (age < 60) ...; no error; later ifs overwrite earlier ones (child pays 200)
Wrong order in a ladder checking age < 60 before age < 12 no error; the narrow case is never reached
Missing break case 2: printf("Coffee"); no error; falls through into every case below
switch on a float switch (price) error: switch quantity not an integer
Decimal / variable / range as a case case 1.5: case limit: case age >= 60: error: case label does not reduce to an integer constant

Mini project: chai stall order

#include <stdio.h>

int main() {
    int item, plates, price;
    printf("1 Chai  2 Samosa  3 Lassi: ");
    scanf("%d", &item);
    switch (item) {
        case 1: price = 15; break;
        case 2: price = 20; break;
        case 3: price = 40; break;
        default: price = 0;
    }
    printf("Plates: ");
    scanf("%d", &plates);
    if (price == 0) {
        printf("\nNot on the menu\n");
    } else {
        int total = price * plates;
        if (total >= 100)
            total = total - 10;
        printf("\nTotal: %d\n", total);
    }
    return 0;
}
Input Output
2 then 6 1 Chai 2 Samosa 3 Lassi: Plates: then Total: 110
9 then 1 1 Chai 2 Samosa 3 Lassi: Plates: then Not on the menu
  • The switch turns an item number into a price; default marks "not on the menu" with price 0.
  • The if / else checks for that, and an if inside the else (a nested if) gives ₹10 off orders of ₹100 or more: 6 × 20 = 120, minus 10 = 110.

Practice

  1. Read marks and print a grade: A (90+), B (75+), C (50+), otherwise Fail.
  2. Read a number and print whether it is even or odd.
  3. Read a year and print whether it is a leap year (divisible by 4 but not by 100, or divisible by 400).
  4. A calculator: read a op b (like 7 / 2) and use a switch on the operator. Handle division by zero.
  5. What does this print, and why?
int x = 5;
if (x > 2)
    if (x > 10)
        printf("big\n");
else
    printf("small\n");
Solutions and hints

1. An else if ladder from the highest grade down. Input 82 prints Grade B; input 40 prints Fail.

int marks;
scanf("%d", &marks);
if (marks >= 90)
    printf("Grade A\n");
else if (marks >= 75)
    printf("Grade B\n");
else if (marks >= 50)
    printf("Grade C\n");
else
    printf("Fail\n");

2. Use % (remainder, episode 3). Input 7 prints 7 is odd.

int n;
scanf("%d", &n);
if (n % 2 == 0)
    printf("%d is even\n", n);
else
    printf("%d is odd\n", n);

3. Combine conditions with && and ||. 1900 → 1900 is not a leap year, 2000 → 2000 is a leap year, 2024 → 2024 is a leap year.

int year;
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
    printf("%d is a leap year\n", year);
else
    printf("%d is not a leap year\n", year);

4. " %c" isn't needed here because %c sits between two numbers and the format has spaces around it. Input 7 / 2 prints 3.50; 5 / 0 prints Cannot divide by zero; 3 x 4 prints Unknown operator x.

float a, b;
char op;
scanf("%f %c %f", &a, &op, &b);
switch (op) {
    case '+': printf("%.2f\n", a + b); break;
    case '-': printf("%.2f\n", a - b); break;
    case '*': printf("%.2f\n", a * b); break;
    case '/':
        if (b == 0) printf("Cannot divide by zero\n");
        else printf("%.2f\n", a / b);
        break;
    default: printf("Unknown operator %c\n", op);
}

5. It prints small. An else always belongs to the nearest unmatched if (here if (x > 10)), whatever the indentation says. This is the "dangling else". 5 > 2 is true, 5 > 10 is false, so the inner else runs. Braces make your intent explicit.

Quick quiz

What does this print?

int x = 2;
switch (x) {
    case 1: printf("A");
    case 2: printf("B");
    case 3: printf("C");
            break;
    default: printf("D");
}
  • A. B
  • B. BC
  • C. BCD
  • D. D
Answer

B: BC. switch jumps to case 2 and prints B. There's no break, so it falls through into case 3 and prints C; then the break stops it before default.

Interview questions

  • What values does C treat as true and false in an if condition?
  • What is the difference between = and ==? Why does if (x = 5) compile?
  • Some programmers write if (60 == age) ("Yoda condition"). Why?
  • What is the dangling-else problem and how do braces solve it?
  • What is fall-through in switch? When is it useful?
  • What types can a switch expression have? Why can't a case label be a variable?
  • When would you choose switch over an else if ladder, and vice versa?
  • What is the ternary operator? Can it replace every if / else?

Glossary

Term Meaning Example
Condition An expression C checks to decide; 0 is false, anything else is true got == 0
if Runs a statement or block only when its condition is true if (age >= 60) { ... }
else The path taken when the if condition is false } else { ... }
Block Statements grouped with { } so they act as one { printf("A"); printf("B"); }
Empty statement A lone ; that does nothing if (x > 0);
else if ladder A chain of conditions checked in order; stops at the first true one if (a) ... else if (b) ... else ...
Nested if An if inside another if or else the discount check in the mini project
Dangling else An else binds to the nearest unmatched if practice question 5
Ternary operator cond ? a : b, a value chosen by a condition int p = (age >= 60) ? 120 : 200;
switch Jumps to the case matching one integer value switch (choice) { ... }
case label An entry point inside a switch; must be an integer constant case 2:
break Leaves the switch (or a loop) immediately case 2: ...; break;
default The switch path for any value with no matching case default: printf("Not on the menu");
Fall-through Running into the next case because there's no break missing breaks print every item below
Integer constant A fixed whole number or character known at compile time 1, 'S'

Summary

  • A program is a straight road; if is a fork. With else, exactly one path runs.
  • A condition is a number: 0 is false, anything else is true.
  • Silent traps: = vs ==, a ; after the condition, and missing braces. Always use { }.
  • An else if ladder stops at the first true condition, so order matters.
  • cond ? a : b picks one of two values in one line.
  • switch jumps to the matching case; end each case with break (unless you want fall-through) and add a default. Case labels must be integer constants.

Next episode: loops. Our chai stall program now decides, but it takes one order and stops. Next time the program repeats, with while, for and do-while.