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
To run certain code when a condition is true you use the if statement. The condition is written inside parentheses and, if true, the block wrapped in braces runs: if (age >= 18) { std::cout << "Can drive"; }.
C++ does not use a then keyword; the parentheses and the brace block are enough. The condition must evaluate to a bool value, which the comparison operators produce. When the condition is false the block is skipped and the program moves to the next statement.
Comparison operators
Inside if conditions you often use comparison operators. == is equal, != is not equal, < is less than, > is greater than, <= is less than or equal, >= is greater than or equal.
Note: = is assignment and == is comparison. If you write if (count = 0) you reset count to zero and the result is false, so the block does not run. Always use double == for comparison.
Practice Age check
The age variable is set to 20. Use the condition if (age >= 18) to check whether the age is 18 or above and, if true, print "Can drive".
Starter code
#include <iostream>
int main() {
int age = 20;
// Write the age check here
return 0;
}Sample solution
#include <iostream>
int main() {
int age = 20;
if (age >= 18) {
std::cout << "Can drive" << std::endl;
}
return 0;
}Expected output
Can drive
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid if statement?
if (... ) { ... }- if (age >= 18) { ... } Correct answer
- if age >= 18 { ... }
- if (age >= 18) then { ... }
- if [age >= 18] { ... }
Explanation: The condition is in parentheses; no 'then' keyword.
2 Write the if condition
int age = 20;
if (____) { std::cout << "Access granted"; }
int age = 20;
if (age >= 18) { std::cout << "Access granted"; }
Explanation: age >= 18 is true for 20.
3 Match each operator to its meaning
| Term | Meaning |
|---|---|
== |
Equal |
!= |
Not equal |
< |
Less than |
>= |
Greater or equal |