← Back to C++ Course | Chapter 2: Input & Output | Lesson 2 of 8

C++ Print Numbers

cout << can print numeric literals and the results of expressions directly, and setprecision/setw from iomanip offer extra control over decimal places and field width.

Printing Numeric Literals

cout << can print numeric literals directly, without any conversion, and will display the number exactly as written, whether it's a whole integer or a decimal value.

Example: Printing Numeric Literals

cpp
#include <iostream>

int main() {
	std::cout << 42 << std::endl;
	std::cout << 3.14 << std::endl;
	return 0;
}

Printing Arithmetic Results

When cout is given a mathematical expression, C++ evaluates that expression completely first and only then prints the single resulting number, not the original expression text.

Example: Printing Arithmetic Results

cpp
#include <iostream>

int main() {
	std::cout << 5 + 3 << std::endl; // prints 8, not "5 + 3"
	return 0;
}

Printing Different Number Types

cout << works with every numeric type in C++ -- short, int, long, float, and double -- and prints each one formatted according to that type's own conventions.

Example: Printing Different Number Types

cpp
#include <iostream>

int main() {
	short s = 10;
	int i = 1000;
	long l = 100000L;
	float f = 1.5f;
	double d = 3.14159;
	std::cout << s << " " << i << " " << l << " " << f << " " << d << std::endl;
	return 0;
}

Concatenating Numbers with Text

The << operator can be chained multiple times in a single cout statement, mixing string literals and numeric values, and any number combined this way is automatically converted to its printable text form.

Example: Concatenating Numbers with Text

cpp
#include <iostream>

int main() {
	int score = 95;
	std::cout << "Score: " << score << " out of 100" << std::endl;
	return 0;
}

Formatting Numbers in Output

For more control over how a number appears, the iomanip library provides manipulators like setprecision and fixed for a fixed number of decimal places, and setw for a minimum field width.

Example: Formatting Numbers in Output

cpp
#include <iostream>
#include <iomanip>

int main() {
	double price = 19.5;
	std::cout << std::fixed << std::setprecision(2) << price << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.