if and switch
So far, programs have run from top to bottom, every line. This lesson teaches a program to choose: if a condition holds, do this; if not, do that, or skip it altogether.
1#include <stdio.h>2 3int main(void) {4 int temp = 31;5 if (temp > 30) {6 printf("Hot today, drink some water\n");7 }8 printf("It is %d degrees\n", temp);9 return 0;10}
Hot today, drink some water It is 31 degrees
The condition goes in the parentheses after if. When it holds, the block in curly braces runs; when it doesn't, the block is skipped. The last printf is outside the if, so it runs either way. Change 31 to 25 and run it again.
Comparing two values
Most conditions use a comparison operator:
| You write | It means |
|---|---|
a == b | equal to (two equals signs) |
a != b | not equal to |
a < b | less than |
a > b | greater than |
a <= b | less than or equal to |
a >= b | greater than or equal to |
A comparison gives back an integer: 1 when it holds, 0 when it doesn't. You can print it with %d:
1#include <stdio.h>2 3int main(void) {4 int a = 7;5 int b = 10;6 printf("%d\n", a < b);7 printf("%d\n", a == b);8 printf("%d\n", a != b);9 printf("%d\n", a >= 7);10 return 0;11}
1 0 1 1
if and else
To do something when the condition does not hold, add else. Exactly one of the two blocks runs:
1#include <stdio.h>2 3int main(void) {4 int score = 58;5 if (score >= 60) {6 printf("Pass\n");7 } else {8 printf("Fail, %d points short\n", 60 - score);9 }10 printf("Score recorded\n");11 return 0;12}
Fail, 2 points short Score recorded
Press Step and watch which lines the program skips.
Tip: When a block holds a single statement, you may leave out the curly braces, but it's better to always write them. Then adding a second line later can't go wrong because you forgot to add the braces.
More choices: else if
For several cases, chain them with else if. The program tries them from top to bottom; the first one that holds runs its block, and the rest are not even looked at:
1#include <stdio.h>2 3int main(void) {4 int score = 85;5 if (score >= 90) {6 printf("Excellent\n");7 } else if (score >= 75) {8 printf("Good\n");9 } else if (score >= 60) {10 printf("Pass\n");11 } else {12 printf("Fail\n");13 }14 return 0;15}
Good
85 also meets score >= 60, but only "Good" is printed: an earlier condition already held, so the later ones are never tried. That is why the order matters.
What does this program print?
1#include <stdio.h>2 3int main(void) {4 int score = 95;5 if (score >= 60) {6 printf("Pass\n");7 } else if (score >= 90) {8 printf("Excellent\n");9 }10 return 0;11}
The program tries score >= 60 first. It holds, so it prints "Pass" and skips the else if. For 95 to print "Excellent", the stricter condition score >= 90 has to come first.
And, or, not
You can join conditions together:
| You write | It means | It holds when |
|---|---|---|
a && b | and | both sides hold |
a || b | or | at least one side holds |
!a | not | a does not hold |
1#include <stdio.h>2 3int main(void) {4 int temp = 22;5 int age = 70;6 if (temp >= 18 && temp <= 26) {7 printf("Nice temperature\n");8 }9 if (age < 12 || age >= 65) {10 printf("Half-price ticket\n");11 }12 if (!(temp > 30)) {13 printf("No need for the AC\n");14 }15 return 0;16}
Nice temperature Half-price ticket No need for the AC
In math you write 18 <= temp <= 26; in C you write temp >= 18 && temp <= 26. Writing 18 <= temp <= 26 does compile, but it means something else entirely: first 18 <= temp gives 0 or 1, then that number is compared with 26, which always holds.
Truth is a number
C has no separate "true" and "false": a condition is just a number. 0 is false, and any number that isn't 0 is true, negative ones included. So a number can be a condition on its own:
1#include <stdio.h>2 3int main(void) {4 int stock = 0;5 if (stock) {6 printf("In stock\n");7 } else {8 printf("Sold out\n");9 }10 printf("%d\n", !stock);11 printf("%d\n", -3 && 5);12 return 0;13}
Sold out 1 1
stock is 0, so it is false; !stock turns false into true and gives 1. -3 and 5 are both nonzero, so both sides of && are true and the result is 1.
= is not ==
= assigns; == compares. Leaving out one equals sign inside an if is one of the most common mistakes in C:
1#include <stdio.h>2 3int main(void) {4 int score = 70;5 if (score = 100) {6 printf("Perfect score!\n");7 }8 printf("score is now %d\n", score);9 return 0;10}
Perfect score! score is now 100
score = 100 does not ask "is score 100?"; it puts 100 into score. The value of that expression is 100, which isn't 0, so the condition holds. A score of 70 gets "Perfect score!", and score has been changed to 100. Change = to == and run it again.
Tip: When a program runs but gives the wrong result, check your if conditions for a missing equals sign.
switch: one case per value
To compare one integer against a few fixed values, switch reads more clearly:
1#include <stdio.h>2 3int main(void) {4 int day = 6;5 switch (day) {6 case 1:7 case 2:8 case 3:9 case 4:10 case 5:11 printf("Workday\n");12 break;13 case 6:14 case 7:15 printf("Weekend\n");16 break;17 default:18 printf("No such day\n");19 }20 return 0;21}
Weekend
switch finds the case equal to day, starts running from there, and leaves the switch at the first break. Several case lines in a row share the same code. When no case matches, default runs.
A case takes only a fixed integer or character (like 'A'): not a variable, and not a decimal number.
**Forget the break** and the program doesn't stop: it carries on into the code of the next case. This is called "falling through":
1#include <stdio.h>2 3int main(void) {4 char grade = 'B';5 switch (grade) {6 case 'A':7 printf("Excellent\n");8 case 'B':9 printf("Good\n");10 case 'C':11 printf("Pass\n");12 default:13 printf("Keep going\n");14 }15 return 0;16}
Good Pass Keep going
grade is 'B', so it starts at case 'B', but there isn't a single break, so it falls all the way to the end and prints three lines. Press Step to watch it fall. The last exercise of this lesson is a switch like this one for you to fix.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Odd or even
✓Use if and else to tell whether n is odd or even. With n at 7, print 7 is odd; changed to 8, it should print 8 is even.
7 is odd
1#include <stdio.h>2 3int main(void) {4 int n = 7;5 6 return 0;7}
Cold, comfortable or hot
✓Below 18 degrees, print Cold; from 18 to 26 (both included), print Comfortable; above 26, print Hot. temp is 27.
Hot
1#include <stdio.h>2 3int main(void) {4 int temp = 27;5 6 return 0;7}
Fix the traffic light
✓light is 'Y' (yellow), yet the program prints several lines. Fix it so it prints only Slow down.
Slow down
1#include <stdio.h>2 3int main(void) {4 char light = 'Y';5 switch (light) {6 case 'R':7 printf("Stop\n");8 case 'Y':9 printf("Slow down\n");10 case 'G':11 printf("Go\n");12 default:13 printf("Unknown light\n");14 }15 return 0;16}
What you learned
- The comparison operators
==!=<><=>=give1(holds) or0(doesn't). if/else if/elseare tried from top to bottom, and only the first block whose condition holds runs, so the order matters.&&is and,||is or,!is not; write a range astemp >= 18 && temp <= 26.- In C,
0is false and any nonzero number is true. =assigns and==compares;if (x = 100)always holds, and it changesxtoo.switchpicks a case by an integer or character value; end eachcasewithbreak, or it falls through to the next one.