C Workshop · Positive or Negative
Lesson C

Positive or Negative

Read n and classify it as Positive, Negative, or Zero.

What it is

You read one integer and classify it: greater than zero, less than zero, or exactly zero. Three labels, one winner. This is the most common three-way if in beginner C.

Approach

  1. scanf one integer.
  2. if (n > 0) print Positive.
  3. else if (n < 0) print Negative.
  4. else print Zero.

Where this is used in the real world

Diagram

1

scanf

-3

2

tests

>, then <

3

match

n < 0

4

output

Negative

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;
4    scanf("%d", &n);
5    if (n > 0) printf("Positive\n");
6    else if (n < 0) printf("Negative\n");
7    else printf("Zero\n");
8    return 0;
9}
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. Input -3 prints:

else if (n < 0).

2. The Zero branch runs when:

Final else.

3. Order of tests should be:

No overlap.

4. scanf reads into n with:

Address.

5. else if is skipped when:

First true wins.