Loading
0x50Lesson 6 of 20

Making decisions: if and switch

Make your program choose what to do with if, else, logical operators and switch.

12 min 6-question quiz 2 code exercises
By the end of this lesson you can
  • Branch with if, else if and else
  • Combine conditions with &&, || and !
  • Use switch for many fixed cases - and remember break

So far, programs have run every line top to bottom. Control flow lets a program choose which lines run. The simplest tool is if: run a block only when a condition is true.

if, else if, else

grade.c
1#include <stdio.h>
2
3int main(void) {
4    int score = 83;
5
6    if (score >= 90) {
7        printf("A\n");
8    } else if (score >= 80) {
9        printf("B\n");
10    } else if (score >= 70) {
11        printf("C\n");
12    } else {
13        printf("Keep practicing\n");
14    }
15    return 0;
16}
Output
B

The conditions are checked in order, and only the first true branch runs. That is why score >= 80 does not also need score < 90: if the score were 90 or more, the first branch would already have run. Try changing score and running it again.

What counts as true

C has no special boolean type in its core: zero is false, and any non-zero value is true. Comparisons produce 1 or 0. Since C99 you can #include <stdbool.h> to get bool, true and false, which make intent clearer - use them.

Combining conditions

  • a && b is true when both are true.
  • a || b is true when at least one is true.
  • !a flips true and false.

Both && and || short-circuit: they stop as soon as the answer is known. In count > 0 && total / count > 10, the division never happens when count is 0 - a handy way to guard against dividing by zero.

ticket.c
1#include <stdio.h>
2#include <stdbool.h>
3
4int main(void) {
5    int age = 15;
6    bool with_adult = true;
7
8    if (age >= 18 || with_adult) {
9        printf("Entry allowed\n");
10    }
11    if (age >= 13 && age <= 19) {
12        printf("Teen ticket\n");
13    }
14    return 0;
15}
Output
Entry allowed
Teen ticket

switch

When you compare one integer (or char) against many fixed values, switch is cleaner than a long if chain:

menu.c
1#include <stdio.h>
2
3int main(void) {
4    char choice = 's';
5
6    switch (choice) {
7        case 'n':
8            printf("New game\n");
9            break;
10        case 'l':
11            printf("Load game\n");
12            break;
13        case 's':
14            printf("Settings\n");
15            break;
16        default:
17            printf("Unknown option\n");
18            break;
19    }
20    return 0;
21}
Output
Settings

Each case label marks where execution starts. Without break, it keeps going into the next case - called fall-through. Occasionally that is what you want (several cases sharing one block), but forgetting a break is a very common bug. default runs when no case matches.

Key takeaways

  • if / else if / else checks conditions in order and runs only the first true branch.

  • Zero is false, anything else is true. && and || short-circuit. Write ranges as x > 0 && x < 10.

  • switch jumps to a matching case; end each case with break unless you truly want fall-through.

Lesson quiz

6 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning C.

Exercise 1

FizzBuzz for one number

+25 XP

Read one integer. Print FizzBuzz if it is divisible by both 3 and 5, Fizz if only by 3, Buzz if only by 5, and otherwise the number itself.

  • 15 prints FizzBuzz
  • 9 prints Fizz
  • 10 prints Buzz
  • 7 prints 7
main.c
Loading editor…

Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Exercise 2

Tiny calculator

+25 XP

Read an expression like 12 * 3 - a number, an operator character, and a number - and print the result. Support +, -, * and / using a switch. For division by zero, print Error: division by zero. For any other operator, print Error: unknown operator.

Read it with scanf("%d %c %d", &a, &op, &b). Integer division is fine.

  • 12 * 3
  • 20 / 6
  • 5 / 0
  • 2 ^ 3
main.c
Loading editor…

Your code is compiled with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…