C If...Else and Switch
Conditions let a C program take different paths depending on values.
The if Statement
Example
#include <stdio.h>
int main(void) {
int temperature = 40;
if (temperature > 35) {
printf("It is very hot today. Drink water!\n");
}
return 0;
}It is very hot today. Drink water!
if, else if and else
C checks each condition from top to bottom and runs the first block that is true:
Example
#include <stdio.h>
int main(void) {
int units = 250; // electricity units used
if (units <= 100) {
printf("Low usage\n");
} else if (units <= 300) {
printf("Normal usage\n");
} else {
printf("High usage\n");
}
return 0;
}Normal usage
True and False in C
C has no separate boolean type in older code. Any non-zero number counts as true, and 0 counts as false. Since C99 you can include <stdbool.h> and use bool, true and false:
Example
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool isMember = true;
if (isMember) {
printf("You get a 10%% discount\n");
}
return 0;
}You get a 10% discount
To print a % sign with printf, write %%.
The Ternary Operator
A short form of if...else that picks one of two values:
Example
int n = 7;
printf("%s\n", (n % 2 == 0) ? "Even" : "Odd");Odd
The switch Statement
switch compares one whole number (or a char) with a list of fixed values:
Example
#include <stdio.h>
int main(void) {
char choice = 'b';
switch (choice) {
case 'a':
printf("Biryani\n");
break;
case 'b':
printf("Nihari\n");
break;
case 'c':
printf("Haleem\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}Nihari
| Part | Purpose |
|---|---|
case | One value to match |
break | Leaves the switch |
default | Runs when nothing matches |
Without break, C continues into the next case. Sometimes this is useful, but usually it is a bug.
A Common Mistake
Writing = instead of == inside a condition sets the value instead of comparing it:
Example
int x = 5;
if (x = 0) { // wrong: x becomes 0, and 0 is false
printf("zero\n");
}Always use == to compare.
Exercise
Exercise
In C, which value is treated as false in a condition?
