Summary
In this lesson, you learned that:
- A variable has a data type, a name and a value:
int score = 25;. Creating a variable is called a declaration. =doesn't mean “equals”, but “store”: the value on the right is stored in the variable on the left.- Giving a variable a value when you create it is initialization. Storing a different value in it later is assignment, and it's written without the type:
score = 30;. A variable without a value holds nonsense, so always initialize your variables. - Names are written in camelCase (
ticketPrice) without accents. They can't start with a digit or contain spaces, and uppercase and lowercase letters matter. - The basic data types are
int(a whole number),double(a decimal number, with a point),char(one character in single quotes),bool(trueorfalse, printed as1and0) andstd::string(text in double quotes, needs#include <string>). - With
<<, you print text and variables one after another.<<doesn't add spaces; they go inside the quotes. - The arithmetic operators are
+,-,*,/and%. Multiplication, division and the remainder are done before addition and subtraction; parentheses change the order. - Dividing two whole numbers gives a whole number:
7 / 2is3, and7 % 2(the remainder) is1. You get a decimal result when at least one number is a decimal number (7.0 / 2is3.5), or withstatic_cast<double>(...). - You can calculate a variable's new value from its current one:
score = score + 10;, or shorter,score += 10;.-=,*=and/=work the same way.++adds 1, and--subtracts 1. +and+=join texts of typestd::string, but not two texts in quotes, and not text and a number.
In the next lesson, your programs will learn to make decisions: to do one thing or another, depending on the values of variables.
Instructions
- 1
Before you go on, try it all out on a small task: a program for a cinema.
The screening takes longer than the film itself, because ads run before it. Add
adstolengthwith+=. - 2
Print the name of the film and the length of the screening in whole hours and the minutes left over. Calculate the hours with
/and the minutes with%:The Lord of the Rings: 3 h 10 min - 3
On the next line, print when the screening ends. Tip: convert the start to minutes since midnight, add the length of the screening, and convert the result back to hours and minutes.
Ends at 22:40