The if Statement
So far, your programs have run every statement, one after another, from top to bottom. But a program often has to decide what to do: show a warning only if a password is too short, or give a discount only if the customer is a student. We make decisions like this all the time: if it rains, I'll take an umbrella.
In C++, a decision is written with the if statement:
int temperature = 30;
if (temperature > 25) {
std::cout << "It's hot, take a cap" << std::endl;
}
std::cout << "Have a nice day" << std::endl;This prints:
It's hot, take a cap
Have a nice dayThe if statement has three parts:
- the keyword
if. A keyword is a word with a special meaning in C++, which is why you can't use it as a variable name; - the condition in parentheses:
(temperature > 25). A condition is a question that can only be answered yes (true) or no (false): is the temperature greater than 25? The parentheses around the condition are required; - the block of code in curly braces
{ }. The block runs only if the condition is true.
After the block, the program continues as usual, so Have a nice day is printed either way. If temperature were 10, the condition would be false: the program would skip the block and print only Have a nice day.
In a condition, you can compare with > (greater than) and < (less than), just like in math. You'll meet the other comparison operators in a moment.
There's no semicolon after the ) or after the }. If you forget the parentheses around the condition, the compiler reports error: expected '(' after 'if'. A semicolon after the condition is more treacherous:
int temperature = 10;
if (temperature > 25); {
std::cout << "It's hot, take a cap" << std::endl;
}This prints:
It's hot, take a capAnd it's only 10 degrees. The semicolon after the parenthesis ends the whole if statement, so only an empty statement belongs to the condition. The block in curly braces has nothing to do with the condition and always runs. The program compiles without an error: the compiler only prints a warning about it, and you don't see warnings in this editor.
Instructions
- 1
Below the variable, write an
ifstatement with the conditionmonitorPrice < 4000. In its block, printI'll buy the monitor. - 2
Below the block, write a second
ifstatement with the conditionmonitorPrice > 4000that printsIt's too expensive. Run the program: it still prints onlyI'll buy the monitor, because 3000 isn't greater than 4000, so the second block is skipped.