Summary
In this lesson, you learned that:
- The
ifstatement runs its block of code only if its condition is true. The condition goes in parentheses, the block in curly braces, and there's no semicolon after the). - The curly braces decide what belongs to the block. The compiler doesn't need the indentation by 4 spaces, but it shows you and others which lines belong to the block, so we always use it.
elseadds a second branch, which runs when the condition is false, andelse ifadds more branches with conditions of their own. The program checks the conditions from top to bottom and runs only the first true one, so their order matters.- Comparison operators compare two values:
==,!=,>,<,>=and<=. Twostd::stringtexts are equal only if they match exactly, including upper and lower case. =assigns a value, while==compares.if (points = 10)compiles, but it stores 10 inpoints, and the condition is then always true.- Every comparison gives a boolean value,
trueorfalse, which you can store in aboolvariable and use as a condition.std::coutprints it as1or0. A number is even whennumber % 2 == 0. - Logical operators combine conditions:
&&(and) is true when both parts are true,||(or) when at least one is, and!(not) turnstrueintofalseand back. Each part must be a complete comparison. Parentheses group conditions; without them,&&goes before||. - An
ifstatement can be nested in the block of anotherif. Two nestedifstatements withoutelsecan be rewritten as a single one with&&.
Next comes a small project, in which you'll try out everything from the first three lessons on your own. Then, in the lesson on vectors, you'll learn to store many values in a single variable, a vector: a shopping list, for example, or the scores of a whole class.
Instructions
- 1
Practice: a zoo ticket costs 150. Children under 6 get in for free, children under 18 pay 80, and seniors aged 65 or more pay 100. Above the last line, write an
ifstatement withelse ifbranches that changespriceto0,80or100. With an age of 15, the program printsTicket price: 80. - 2
Check the youngest visitors: change
ageto4. The program must printTicket price: 0. If it printsTicket price: 80, look at the order of your conditions.