The if statement
- C course
- Beginner
- Lesson 36/116
- 4 min
Learn how to check a condition with if and the code block.
The if statement
The if statement runs a code block when a condition is true. The condition goes in parentheses; if it's true (non-zero) the block runs.
int score = 80;
if (score >= 50) {
printf("Passed\n");
}Here >= is a comparison operator. Common operators: == equal, != not equal, < less, > greater, <= less or equal, >= greater or equal. When the condition is false the block is skipped.
Single-line if
When the block has a single statement, braces are optional. But using them is a good habit; adding a statement later won't break anything.
int n = 7;
if (n % 2 == 0)
printf("Even\n");
if (n % 2 != 0)
printf("Odd\n");The % operator gives the division remainder; n % 2 is used to check even/odd. Each if is independent; both may run.
Practice Is the number even or odd?
Write a C program. Declare int n = 7;. Use if to check n % 2 == 0; if true print printf("Even\n");. Also use if to check n % 2 != 0; if true print printf("Odd\n");. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare n, check even/odd
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int n = 7;
if (n % 2 == 0) {
printf("Even\n");
}
if (n % 2 != 0) {
printf("Odd\n");
}
return 0;
}Expected output
Odd
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does if (score >= 50) run?
if (score >= 50) {
printf("Passed");
}- When score is 50 or greater Correct answer
- When score is less than 50
- Always
- Never
Explanation: >= accepts 50 and above.
2 Write the equality operator
if (a ____ b) {
printf("Equal");
}
if (a == b) {
printf("Equal");
}
Explanation: == checks equality, = assigns.
3 Match the operators
| Term | Meaning |
|---|---|
== |
Equal |
!= |
Not equal |
>= |
Greater or equal |
< |
Less |