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
- Start with n is 2
- Do this Is n positive?
- Result yes
#include <stdio.h>
int main(void) {
int n = 2;
if (n > 0) {
puts("yes");
} else {
puts("no");
}
}
yes
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.
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
#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;
}
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.