C Workshop · Conditionals
Foundation C

if / else / switch

A condition chooses which statements run. Only one path is taken on a given input.

What it is

A conditional is a fork in the road. The program looks at a test and then takes only one path: the if body, an else if, or the leftover else. The other paths are skipped completely on this run.

Approach

  1. Read or set the value you will test.
  2. Write mutually exclusive branches (positive / negative / zero).
  3. Print exactly one label.

Where this is used in the real world

Diagram

C chooses a path with if / else or with switch. This run uses if / else if / else.

if / else if / else

Open-ended tests: ranges, several variables, or n > 0. First true branch wins.

switch / case

Exact integer (or char) labels. Put break after each case or execution falls through.

ternary ? :

A one-line choose: x = n > 0 ? 1 : -1;. Not a replacement for long if chains.

1

n = -3

the value we test

Could have come from scanf in a real program.
2

n > 0 ?

first test

False, so skip Positive.
3

n < 0 ?

second test

True, so this branch owns the output.
4

printf Negative

the taken path

Zero is never printed.

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3    int n = -3;
4    if (n > 0) printf("Positive\n");
5    else if (n < 0) printf("Negative\n");
6    else printf("Zero\n");
7    return 0;
8}
What this line does
Press Run algorithm. The highlight will move through the C code.
True branch
the if body runs
False branch
else / skip
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. How many branches print for one input?

First true match.

2. Sample n = -3 prints:

n < 0.

3. else is for:

Default path.

4. switch is best when:

Exact cases.

5. if (n = 0) is usually a bug because:

Use ==.