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. We always write the braces, too, even around a single statement.
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<=.=assigns a value, while==compares. On this site,if (points = 10)is a compile error. - With
#include <stdbool.h>, you have the typeboolwith the valuestrueandfalse. You print them with%das1and0. In C, a condition is a number: a comparison gives 1 or 0, 0 means false, and any other number means true. 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) turns true into false and 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&&. switchchooses by the exact value of a whole number or a character: it jumps to the matchingcase,breakends it, anddefaultcatches everything else. Withoutbreak, the program falls through to the nextcase.
In the next lesson, on loops, you'll learn to make a program repeat statements: count to a hundred, for example, or add up a whole series of numbers.
Instructions
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. In place of the comment, write an if statement with else if branches that changes price to 0, 80 or 100. With an age of 15, the program prints Ticket price: 80.
Check the youngest visitors: change age to 4. The program must print Ticket price: 0. If it prints Ticket price: 80, look at the order of your conditions.
Start programming for free
12/12