Beginner level · Module 1: C++ Toolchain and First Programs · Lesson 3 of 3
Types, Variables and Input/Output
Store values in typed variables, calculate with operators and read and print values with iostream.
In this lesson you will
- Choose suitable fundamental types and std::string
- Read input with std::cin and format output with std::cout
Key concepts
int, double, bool, charstd::stringinteger divisionstd::cin and std::cout
The lesson
C++ is statically typed: int for whole numbers, double for decimals, bool for true/false, char for one character and std::string for text. Initialise every variable when you declare it — int count{0}; — because an uninitialised local variable holds an unpredictable value.
Integer division drops the remainder: 7 / 2 is 3, while 7 / 2.0 is 3.5. The % operator gives the remainder. Mixing types converts values automatically, which can hide mistakes; the compiler warnings help here.
std::cout << "Total: " << total << '\n'; prints values. std::cin >> distance; reads a number; std::getline(std::cin, name) reads a whole line of text. Formatting decimals uses <iomanip>: std::fixed << std::setprecision(2).
Step by step
- Declare and initialise variables of each fundamental type.
- Calculate a total and an average and print them.
- Read two numbers with std::cin.
- Print a decimal with two places using std::fixed and std::setprecision.
Practice activity
Write the trip-cost calculator from the practical activity, printing litres needed and cost in SSP with two decimals.
Expected result: For 190 km at 9 litres per 100 km and 1,250 SSP per litre, the program prints 17.10 litres and 21375.00 SSP.
Check your understanding
-
Why initialise every local variable?
Show answer
An uninitialised local variable holds an unpredictable value.
-
What is 9 / 4 when both are int?
Show answer
2.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.