Calculating

In the previous lesson, you calculated with numbers. With variables, it works the same way. 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 ÷), which has a surprise for you in the next exercise

You can store the result in a variable, or print it straight away:

int pencil_price = 2;
int pencils = 6;
int cost = pencil_price * pencils;
printf("Pencils: %d EUR\n", cost);
printf("Change from 20: %d EUR\n", 20 - cost);

This prints:

Pencils: 12 EUR
Change from 20: 8 EUR

When the program gets to the line with cost, it calculates 2 * 6 and stores the result, 12. The variable holds the number, not the calculation: if you changed pencils later, cost would still be 12.

As 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:

printf("%d\n", 2 + 3 * 4);
printf("%d\n", (2 + 3) * 4);

This prints:

14
20

In 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 = 70;
int second = 90;
printf("%d\n", first + second / 2);

The program prints 115, because only the second score is divided by two: 70 + 90 / 2 is 70 + 45. The right way is (first + second) / 2, which gives 80.

More things to watch out for:

  • You always have to write the multiplication. 2(a + b) ends with the error called object type 'int' is not a function or function pointer; write 2 * (a + b).
  • Spaces around operators don't change the result. We write them because they make the code easier to read.
  • An int has a limit: the biggest number it holds is 2147483647, about two billion (and the smallest is about minus two billion). If a result doesn't fit, the program stops with RuntimeError: unreachable. The message doesn't say much, so remember it: for now, it means that a number has grown too big.

Instructions

Three of you are going to the cinema, and each of you buys a ticket and popcorn. Below, 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 EUR

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/11