else if, && and ||
Read · 1 of 5
Checked top to bottom
In a chain of if … else if … else, C checks each condition in order and runs only the first block whose condition is true.
&& means both must be true, || means at least one, ! flips true and false. marks >= 40 && marks < 60 is true for 40 to 59.
Read this lesson as text
Choose between many options and combine conditions.
Checked top to bottom
In a chain of if … else if … else, C checks each condition in order and runs only the first block whose condition is true.
&& means both must be true, || means at least one, ! flips true and false. marks >= 40 && marks < 60 is true for 40 to 59.
First match wins
#include <stdio.h>
int main() {
int t = 35;
if (t > 20) {
printf("warm\n");
} else if (t > 30) {
printf("hot\n");
} else {
printf("cool\n");
}
return 0;
}What does this print?
- warm
- hot
- warm hot
Show the answer
warm 35 > 20 is already true, so the chain stops there. Put the strictest check first.
Exercise: Marks to grade
Read marks (0 to 100) and print the grade: 75 and above A, 60 to 74 B, 40 to 59 C, below 40 F.
Exercise: Leap year
Read a year and print Leap or Not leap.
A year is a leap year if it divides by 4, except years that divide by 100, unless they also divide by 400.
Break it: Break the biggest-of-three
This should print the biggest of three numbers. Find an input where it prints the wrong one.
#include <stdio.h>
int main() {
int a, b, c, max;
scanf("%d %d %d", &a, &b, &c);
if (a > b) max = a;
if (b > c) max = b;
else max = c;
printf("%d\n", max);
return 0;
}Input rules: three whole numbers between -1000 and 1000, separated by spaces.