DMarlon Studio

Lesson 6 · 6 of 20

Decisions with if and switch · C

Make decisions in C with if, else if and else, and pick between several cases with switch, case, break and default: temperatures, scores and opening hours.

C · Decisions with if and switch in DMarlon Studio: the example's code and its output in the terminal

`if` runs a statement or a block only when the condition in brackets is true. At 31 degrees, temperature > 30 holds and the warning is printed. With a single statement the braces can be left out, as here; with several, they are required.

`else if` and `else` pick one path among several. C tries the conditions from top to bottom and runs only the first block that matches: with 68, the first one (>= 90) fails, the second one (>= 60) holds and the else is never looked at.

`switch` compares a whole number with several fixed case values. Cases written one after another share the same code: days 1 to 5 open at 9:00, and 6 and 7 are the weekend. `default` catches any other value.

Each case ends with `break`. Without it, C would carry on running the code of the next case, a very common mistake. Try changing day to 3 or 9 and run it again.

Code · main.c

#include <stdio.h>int main(void) {    // if runs its block only when the condition is true.    int temperature = 31;    if (temperature > 30)  // one statement: braces are optional        printf("%d degrees: it is hot, drink water.\n", temperature);    // else if and else choose one path among several.    int score = 68;    if (score >= 90) {        printf("Score %d: excellent\n", score);    } else if (score >= 60) {        printf("Score %d: passed\n", score);    } else {        printf("Score %d: try again\n", score);    }    // switch compares one whole value with fixed cases.    int day = 6;    switch (day) {        case 1: case 2: case 3: case 4: case 5:            printf("Day %d: the shop opens at 9:00\n", day);            break;  // without break, the next case would run too        case 6: case 7:            printf("Day %d: weekend, the shop opens at 10:00\n", day);            break;        default:            printf("Day %d does not exist\n", day);    }    return 0;}

Output · cc main.c -o main && ./main

31 degrees: it is hot, drink water.
Score 68: passed
Day 6: weekend, the shop opens at 10:00

Key points

  • if (condition) runs the block when it is true.
  • else if and else pick a single path.
  • switch compares a whole number with fixed values.
  • Every case needs its break.
  • default handles the values you did not expect.

Exercise

Add a switch on a char size variable that prints the price of a coffee by size: 'S' 1.20, 'M' 1.60, 'L' 2.00 and, in default, «Unknown size».