C - Conditional Statements

Conditional statements allow your program to make decisions based on boolean expressions.

Learning Objectives

  • Use if, if-else, and else if ladders.
  • Choose between if chains and switch.

Prerequisites

if / else

#include <stdio.h>

int main(void) {
    int x = 3;
    if (x > 0) {
        printf("positive\n");
    } else {
        printf("non-positive\n");
    }
}

else if ladder

if (score >= 90)      grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else                   grade = 'D';

switch

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

Common Pitfalls

  • Forgetting break in switch causes fall-through.
  • Using assignment = instead of comparison == in conditions.

Checks for Understanding

  1. When would you prefer switch over if-else?
  2. What happens without break in a switch case?
Show answers
  1. When comparing the same variable to many constant values (e.g., chars, small ints).
  2. Execution "falls through" into the next case.