C Language track

Lesson 05 · Level 2: Intermediate

Conditionals

Branching and multiple conditions

Level 2: Intermediate5 min readFree lesson

Conditional statements branch the flow of a program. In this section Learn if/else if/else, the ternary operator, and branching tool sets up to switch.

Learning Objectives

  • Create a multi-level branch with if/else if/else.
  • Use the ternary operator ?: for short condition expressions.
  • Know exactly the operation of switch/case/break/default.
  • Understand the Boolean result of a condition (not 0/0).

Why do you need conditional statements? — "Traffic light at the crossroads"

The program so far has flowed all at once from top to bottom. But in reality, problems almost always look like “sometimes A, other times B”.

            ┌──────────┐
            │ score≥90 │── Yes ──► A
            └──────────┘
                  │ No
                  ▼
            ┌──────────┐
            │ score≥80 │── Yes ──► B
            └──────────┘
                  │ No
                  ▼
C or lower

Conditional sentences are the traffic light at this crossroads.

Key concepts

1) if / else if / else

if (score >= 90)      printf("A\n");
else if (score >= 80) printf("B\n");
else if (score >= 70) printf("C\n");
else                  printf("D or lower\n");
  • It checks from top to bottom and executes only the first branch that is true.
  • So, score >= 80 automatically means "more than 80 but less than 90".

2) Ternary operator ?:

int max = (a > b) ? a : b;

if-else Suitable for simple one-line branching. If it's too long, go for regular if.

3) switch / case

switch (op) {
    case '+': result = a + b; break;
    case '-': result = a - b; break;
    default:  printf("Unknown operator\n");
}

Flow:

┌─────► case '+': ─► break ─► (exit switch)
op? ───┼─────► case '-': ─► break ─► (switch exit)
└─────► default ─► (Switch exit)

If there is no break, it will fall-through to the next case. If you don't mean to, don't forget break.

4) Truth value of conditional expression

In C, 0 is false, and any value other than 0 is true.

if (count) { ... }        //Same as count != 0
if (ptr)   { ... }        //Equivalent to ptr != NULL (idiom expression)

See as example

Example 1 — ex01_if.c : Score → Grade

if (score >= 90)      printf("Grade: A\n");
else if (score >= 80) printf("Grade: B\n");
else if (score >= 70) printf("Grade: C\n");
else if (score >= 60) printf("Grade: D\n");
else                  printf("Grade: F\n");

Input: 85

Enter score (0~100): Grade: B

Input: 59

Enter score (0~100): Grade: F

Bottom line: Branches are evaluated from above, so order matters. If you move if (score >= 60) to the top, 90 points also become D.

Example 2 — ex02_ternary.c: Ternary operator

int max = (a > b) ? a : b;
int min = (a < b) ? a : b;
const char *parity = (a % 2 == 0) ? "even number" : "odd number";

Input: 7 3

Enter two integers: Maximum value: 7
Minimum: 3
a is odd

Bottom line: Because ternaries create values, they can be used directly to initialize variables.

Example 3 — ex03_switch.c: Four arithmetic calculator

switch (op) {
    case '+': result = a + b; break;
    case '-': result = a - b; break;
    case '*': result = a * b; break;
    case '/': /*0 After inspection a/b*/ break;
    default:  /*error*/
}

Input: 12 + 5

Enter an expression (e.g. 3 + 4): Result: 17.000

Input: 10 / 0

Enter an expression (e.g. 3 + 4): cannot be divided by 0.

Key: The label case must be an integer constant (characters are also integers). Strings cannot be used.

Example 4 — ex04_nested_if.c: Nested if (leap year determination)

Leap year rule: Multiples of 4, but excluding multiples of 100, again including multiples of 400.

Input: 2024

Enter the year: 2024 is a leap year.

Input: 2100

Enter the year: 2100 is not a leap year.

Bottom line: As nesting deepens, readability decreases dramatically. One floor at a time is recommended.

A different perspective — if-else if is actually a nested if

if (score >= 90)
    /* A */
else if (score >= 80)
    /* B */
else
    /*C or lower*/

is actually the same as:

if (score >= 90) {
    /* A */
} else {
    if (score >= 80) {
        /* B */
    } else {
        /*C or lower*/
    }
}

else if is just an idiom notation for readability and is not a separate keyword.

Common Mistakes

  1. Confusion between == and =: if (x = 0) is always false + side effect.
  2. Semicolon alone: If the semicolon is entered incorrectly, such as if (x > 0);, an empty branch is created.
  3. Missing break: Unintentional fall-through in switch.
  4. Floating point equality comparison: if (a == 0.1) is almost always false. Comparison with error allowed (fabs(a - 0.1) < 1e-9).
  5. else is tied to the nearby if: When nested, if written without braces, it may be attached to if, which is different from what was intended. Always recommend braces.

Cleanup

  • if/else if/else are evaluated from top to bottom, so the order of conditions is important.
  • Ternary ?: is useful for initializing variables in single-line branches.
  • switch/case is used only for integer type (including character) branches. Don't forget break.
  • In a conditional expression, 0 is false, and all values other than 0 are true.
  • If the overlap becomes deep, separate it into a function or flatten the branches.

Try it yourself

cd src
gcc -std=c11 -Wall -o ex01 ex01_if.c        && echo 85   | ./ex01
gcc -std=c11 -Wall -o ex02 ex02_ternary.c   && echo "7 3" | ./ex02
gcc -std=c11 -Wall -o ex03 ex03_switch.c    && echo "12 + 5" | ./ex03
gcc -std=c11 -Wall -o ex04 ex04_nested_if.c && echo 2000 | ./ex04

Application:

  • Try deleting '+': result = a + b; and break from ex03_switch.c. Observe how the output changes.
  • Write the grade branching condition of ex01_if.c backwards as <= 89 to get the same result.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/ex01_if.cC
#include <stdio.h>

int main(void) {
    int score;
    printf("Enter score (0~100):");
    scanf("%d", &score);

    if (score < 0 || score > 100) {
        printf("Out of range.\n");
        return 1;
    }

    if (score >= 90)      printf("Grade: A\n");
    else if (score >= 80) printf("Grade: B\n");
    else if (score >= 70) printf("Grade: C\n");
    else if (score >= 60) printf("Grade: D\n");
    else                  printf("Grade: F\n");

    return 0;
}
src/ex02_ternary.cC
#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two integers:");
    scanf("%d %d", &a, &b);

    int max = (a > b) ? a : b;
    int min = (a < b) ? a : b;
    const char *parity = (a % 2 == 0) ? "even number" : "odd number";

    printf("Maximum value: %d\n", max);
    printf("Minimum value: %d\n", min);
    printf("a is %s\n", parity);

    return 0;
}
src/ex03_switch.cC
#include <stdio.h>

int main(void) {
    double a, b, result = 0;
    char op;

    printf("Enter an expression (e.g. 3 + 4):");
    scanf("%lf %c %lf", &a, &op, &b);

    int ok = 1;
    switch (op) {
        case '+': result = a + b; break;
        case '-': result = a - b; break;
        case '*': result = a * b; break;
        case '/':
            if (b == 0) { printf("Cannot be divided by 0.\n"); ok = 0; }
            else result = a / b;
            break;
        default:
            printf("Operator not supported: %c\n", op);
            ok = 0;
    }

    if (ok) printf("Result: %.3f\n", result);
    return 0;
}
src/ex04_nested_if.cC
#include <stdio.h>

/*Leap year determination: multiples of 4, excluding multiples of 100, but including multiples of 400*/
int main(void) {
    int year;
    printf("Enter year:");
    scanf("%d", &year);

    int leap;
    if (year % 4 == 0) {
        if (year % 100 == 0) {
            leap = (year % 400 == 0);
        } else {
            leap = 1;
        }
    } else {
        leap = 0;
    }

    printf("Year %d is %s\n", year, leap ? "It's a leap year." : "It's not a leap year.");
    return 0;
}

Assignment

Problem 1

Take three integers a, b, and c as input and output the largest value.

  • File name: hw01.c

Problem 2

Enter the user's age and print one of the following messages:

  • 0~7: "Infant"

  • 8~13: "Children"

  • 14~19: "Youth"

  • 20~64: "Adult"

  • over 65: "Elderly"

  • File name: hw02.c

Problem 3

Enter a month between 1 and 12 and output the number of days in that month. February is simply treated as having 28 days. Try using switch-fallthrough.

  • File name: hw03.c
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

hw01.cC
#include <stdio.h>

int main(void) {
    int a, b, c;
    printf("Enter three integers:");
    scanf("%d %d %d", &a, &b, &c);

    int max = a;
    if (b > max) max = b;
    if (c > max) max = c;

    printf("Maximum value: %d\n", max);
    return 0;
}
hw02.cC
#include <stdio.h>

int main(void) {
    int age;
    printf("Enter your age:");
    scanf("%d", &age);

    if (age < 0)        printf("Invalid input\n");
    else if (age <= 7)  printf("Infant\n");
    else if (age <= 13) printf("Children\n");
    else if (age <= 19) printf("Youth\n");
    else if (age <= 64) printf("Adult\n");
    else                printf("Old man\n");

    return 0;
}
hw03.cC
#include <stdio.h>

int main(void) {
    int month;
    printf("Enter month (1-12):");
    scanf("%d", &month);

    int days;
    switch (month) {
        case 1: case 3: case 5: case 7:
        case 8: case 10: case 12:
            days = 31; break;
        case 4: case 6: case 9: case 11:
            days = 30; break;
        case 2:
            days = 28; break;
        default:
            printf("Invalid input\n");
            return 1;
    }

    printf("%d month has %d days.\n", month, days);
    return 0;
}

Learn this lesson with a mentor

Work through the C Language track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now