Step 1 of 6
if and else
So far, every line of main ran every time. Real programs need to make decisions: do this if the player is alive, that if they're not. The if statement runs a block of code only when a condition is true.
if (condition) {
// runs only when condition is true
} else {
// runs only when condition is false
}
Exactly one of the two blocks runs. The else part is optional; without it, nothing happens when the condition is false.
#include <stdio.h>
int main(void) {
int temperature;
scanf("%d", &temperature);
if (temperature >= 30) {
printf("hot\n");
} else {
printf("not hot\n");
}
printf("done\n");
return 0;
}
34
hot
done
After the if/else, the program continues with the next line either way, which is why done always prints.
Comparison operators
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
< and > |
less than, greater than |
<= and >= |
less or equal, greater or equal |
A comparison produces 1 for true or 0 for false.
The = versus == trap
= assigns and == compares. if (x = 5) doesn't check whether x is 5: it stores 5 in x, and since 5 is non-zero the condition is always true. The compiler warns about this (using the result of an assignment as a condition without parentheses); when you see that warning, you almost certainly meant ==.
Your task
Read a health value and print alive if it's greater than 0, otherwise dead.
Challenge 2
Read how many bullets are left in the magazine. Print reload if it is exactly 0, otherwise fire.
Challenge 3
Read a player's HP and the damage they are about to take. If they still have more than 0 HP afterwards, print survived with N (N is the HP left). Otherwise print eliminated. Input 100 27 prints survived with 73.