C - If Statement
The if
statement executes a block only when a condition is true (nonzero).
Learning Objectives
- Write simple
if
conditions. - Group multiple statements with braces.
Prerequisites
Syntax
if (condition) {
// statements
}
Example
#include <stdio.h>
int main(void) {
int x = 10;
if (x % 2 == 0) {
printf("even\n");
}
}
Common Pitfalls
- Omitting braces can lead to logic errors when adding more statements later.
Checks for Understanding
- When is
if (x)
true?
Show answers
- When
x
is nonzero.