Introduction to Conditions
In real life, we constantly make decisions based on various conditions:
- If it's raining, I'll take an umbrella
- If it's warm outside, I'll go in a t-shirt
- When I'm hungry, I'll get something to eat
Similarly, in programming we need the program to make decisions and change its behavior according to different situations. This is where conditions come in.
In C++ we use conditions with the if
statement:
int age = 18;
if (age >= 18) {
std::cout << "You are an adult" << std::endl;
}
Basic structure of a condition:
if
- keyword introducing the condition(condition)
- expression that evaluates to true or false{}
- block of code that executes if the condition is true
Here are some ways to use conditions:
- Checking user's age
- Verifying password correctness
- Checking if a number is positive or negative
- Finding out if a user has enough money in their account
- And many other decisions in a program
Instructions
Look at the sample code. Notice that when the temperature is 25 degrees, the text is printed, but when it's 15 degrees, the condition is not met and the text is not printed. In the next exercises we'll learn to use conditions!
Start programming for free
1/10