Lesson 16 +10 XP

Printing Numbers with cout

Printing Numbers with cout

Numbers love cout too - and you don't even need quotes for them.

Direct numbers

cout << 42 << endl;
cout << 3.14 << endl;
  • 42 prints as 42.
  • 3.14 prints as 3.14.

Math right inside the stream

You can calculate and print in one go:

cout << 5 + 3 << endl;   // 8
cout << 5 * 2 << endl;   // 10

The expression (like 5 + 3) is evaluated first, then its result goes to the screen.

Watch out: integer division

cout << 7 / 2 << endl;   // 3  (not 3.5!)

When both numbers are integers, C++ does integer division and drops the remainder. For a decimal result, use a decimal point: 7.0 / 2 gives 3.5.

Mixing text and numbers

String it all together with more <<:

cout << "You earned " << 12 << " points" << endl;

Output: You earned 12 points

TL;DR

  • cout << 42 prints a number directly (no quotes).
  • Print the result of an expression: cout << 5 + 3;
  • Integer division drops the fraction: 7 / 2 is 3.
  • Mix text and numbers by chaining <<.