Lesson contents

C — Branching with if and else

In C, an if statement tests a condition and an else branch handles the remaining cases. A chain of else if tests selects the first condition that evaluates as true.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
lesson.c
#include <stdio.h>

int main(void) {
    int n = 2;
    if (n > 0) {
        puts("yes");
    } else {
        puts("no");
    }
}
Output
yes
Advertisements

Classify a stock level

Each condition is tested in order. The variable status points to a string literal, and puts adds a newline. C treats zero as false in a condition, so an explicit stock == 0 test makes the inventory rule clear.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

C17. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 lesson.c -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    int stock = 3;
    const char *status;
    if (stock == 0) {
        status = "sold out";
    } else if (stock <= 5) {
        status = "order soon";
    } else {
        status = "in stock";
    }
    puts(status);
    return 0;
}
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

GNU C Language Manual

Related tags

  • C
  • conditions
  • branching
  • comparison