Title here
Summary here
Branching with if
and else
in C is straightforward.
#include <stdio.h>
int main() {
// Here's a basic example.
if (7 % 2 == 0) {
printf("7 is even\n");
} else {
printf("7 is odd\n");
}
// You can have an `if` statement without an else.
if (8 % 4 == 0) {
printf("8 is divisible by 4\n");
}
// Logical operators like `&&` and `||` are often
// useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0) {
printf("either 8 or 7 are even\n");
}
// In C, you can't declare variables in the if statement,
// so we declare it before the condition.
int num = 9;
if (num < 0) {
printf("%d is negative\n", num);
} else if (num < 10) {
printf("%d has 1 digit\n", num);
} else {
printf("%d has multiple digits\n", num);
}
return 0;
}
To compile and run the program:
$ gcc if-else.c -o if-else
$ ./if-else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that in C, you need parentheses around conditions, and the braces are optional for single-statement blocks (though using them is generally recommended for clarity).
C doesn’t have a ternary if operator like ?:
, but it does have the ternary conditional operator, which can be used for simple conditional expressions:
int x = (condition) ? value_if_true : value_if_false;
However, for more complex conditions, a full if
statement is necessary.