Arithmetic
C++ can calculate. The basic arithmetic operators (symbols for operations) are:
+addition-subtraction*multiplication (an asterisk, because there's no × on the keyboard)/division (a slash instead of ÷)%the remainder after division, which you'll see in the next exercise
You can calculate with numbers and with variables. You can store the result in a variable, or print it straight away:
int pencilPrice = 2;
int pencils = 6;
int cost = pencilPrice * pencils;
std::cout << "Pencils: " << cost << " EUR\n";
std::cout << "Change from 20: " << 20 - cost << " EUR\n";This prints:
Pencils: 12 EUR
Change from 20: 8 EURAs in math, multiplication and division are done before addition and subtraction. Operations with the same priority are done from left to right. If you want a different order, use parentheses:
std::cout << 2 + 3 * 4 << "\n";
std::cout << (2 + 3) * 4 << "\n";This prints:
14
20In the first line, 3 * 4 is calculated first, which is 12, and only then 2 + 12. In the second line, the parentheses come first.
A typical mistake is to forget the parentheses. This doesn't calculate the average of two test scores:
int first = 2;
int second = 4;
std::cout << first + second / 2 << "\n";The program prints 4, because only the second score is divided by two: 2 + 4 / 2 is 2 + 2. The right way is (first + second) / 2, which gives 3.
More things to watch out for:
- You always have to write the multiplication.
2(a + b)ends with the errorcalled object type 'int' is not a function or function pointer; write2 * (a + b). - Anything in quotes is text, and it isn't calculated:
std::cout << "2 + 3";prints2 + 3, not 5. - Spaces around operators don't change the result. We write them because they make the code easier to read.
Instructions
Three of you are going to the cinema, and each of you buys a ticket and popcorn. Create a variable total of type int and store in it how much you pay altogether. Calculate it from the variables: the price of a ticket and popcorn, times the number of people.
Print total like this: Total: 54 EUR. If the program prints 30, look at the order of operations again.
You have a discount coupon for 10 EUR. On the next line, print the price after the discount, calculated from total:
After discount: 44 EURStart programming for free
5/9