Summary

In this lesson, you learned that:

  • A variable has a data type, a name and a value. int age; declares it, and age = 15; stores a value in it. = doesn't mean “equals”, but “store”.
  • Giving a variable a value when you create it is initialization: int age = 15;. Storing a different value later is assignment, written without the type: age = 16;. A variable must get a value before it's used; on this site, anything else is a compile error.
  • Names can contain letters, digits and _, can't start with a digit, can't contain spaces and can't be keywords. Use plain letters without accents. Uppercase and lowercase letters matter. This course writes them in snake_case: total_price.
  • The basic data types are int (a whole number, printed with %d), double (a decimal number with a point, printed with %f, or %.2f for two decimal places) and char (one character in single quotes, printed with %c). A character is stored as a number, its code.
  • One printf can print several values. They fill the format specifiers in order, there must be as many values as specifiers, and each specifier must fit its value.
  • The operators +, -, * and / calculate as in math: multiplication and division first, parentheses change the order. A number too big for an int stops the program with RuntimeError: unreachable.
  • Dividing two whole numbers gives a whole number: 7 / 2 is 3, and 7 % 2 (the remainder) is 1. You get a decimal result when one of the numbers is a decimal number (7 / 2.0), or with a cast: (double)points / games.
  • 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.
  • A constant can't change: const double VAT_RATE = 0.21;. Its name is written in UPPER_CASE. %% prints a percent sign.

In the next lesson, on conditions, your programs will learn to make decisions: to do one thing or another, depending on the values of variables.

Instructions

Before you go on, try it all out on a small task: four friends are going to the cinema, and a ticket costs 8.50 EUR.

Create a variable tickets of type int with the value 4 and a variable price of type double with the value 8.5. Calculate the price of all the tickets and print it like this:

4 x 8.50 = 34.00 EUR

The friends are students, and they get a 15% discount. Create a constant DISCOUNT_PERCENT of type int with the value 15. On the next two lines, print the discount (the price of all tickets times DISCOUNT_PERCENT, divided by 100) and the price after the discount:

Discount 15%: 5.10 EUR
To pay: 28.90 EUR

Start programming for free

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

Or sign up with:

11/11