Booleans and selection: if, else, switch
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
True and false in C
- C has no separate true/false type by default. It uses numbers:
0means false, and any other number means true. - A test like
5 > 3produces1(true).5 < 3produces0(false). - (If you
#include <stdbool.h>you can writebool,true, andfalse— but plainintworks everywhere.)
Comparing and combining
- Compare values with
==(equal),!=(not equal),<,>,<=,>=. - Be careful:
==tests equality; a single=assigns a value. They are different! - Combine tests with
&&(and),||(or), and!(not).a && bis true only when both are true.
if / else if / else
if (test) { ... }runs the block only when the test is true.- Add
else if (...)to check another test, andelsefor "none of the above". - Only the first matching branch runs.
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("Pass\n"); // this one runs
} else {
printf("Fail\n");
}
return 0;
}
switch: choosing among many values
- A
switchpicks a branch based on one value (anintorchar). - Each
caseends withbreak;so it does not fall into the next one.default:catches everything else. switchis neat when you compare the same variable against many fixed values.
Now you try
- Use comparisons and
&&/||to build your tests. Remember0is false, anything else is true. - For the
switchtask, divide the score by 10 first, then switch on the result. - Do not write a
main— the checker provides one.
Complete int sign(int n) so it returns -1 when n is negative, 0 when n is zero, and 1 when n is positive. Do not write a main.
Click Run to see the output here.
Complete int in_range(int n, int lo, int hi) so it returns 1 when n is between lo and hi (inclusive), and 0 otherwise. Use &&. Do not write a main.
Click Run to see the output here.
Complete char grade_letter(int score) using a switch on score / 10. Return 'A' for 90–100, 'B' for the 80s, 'C' for the 70s, 'D' for the 60s, and 'F' below 60. Do not write a main.
Click Run to see the output here.