back to course
Lesson 04 / 716%· free preview
Getting Started4/5
C++ Output
Print to the console with `cout`, `endl`, and `\n` — your bridge to the user.
What is `cout`?
cout (pronounced "see-out") is the standard output stream in C++. It lives in <iostream> and writes text to the terminal/console.
cpp#include <iostream> using namespace std; int main() { cout << "Hello, Codekilla!"; return 0; }
Output: Hello, Codekilla!
The `<<` Insertion Operator
Pour data into the stream with <<. You can chain multiple values:
cppint age = 21; cout << "Age: " << age << " years"; // Age: 21 years
Newlines — `endl` vs `"\n"`
| Form | What it does | Cost |
|---|---|---|
endl | newline + flushes the buffer | slower |
"\n" | newline only | fast — preferred in tight loops |
cppcout << "line1" << endl; cout << "line2\n";
Multi-line Output
Three idiomatic forms:
cppcout << "line 1\n"; cout << "line 2\n"; cout << "line 3\n"; // Or chain with multiple <<: cout << "line 1\n" << "line 2\n" << "line 3\n"; // Or a raw string literal (C++11): cout << R"(line 1 line 2 line 3 )";
Output Formatting (`<iomanip>`)
cpp#include <iomanip> double pi = 3.141592653589; cout << fixed << setprecision(2) << pi; // 3.14 cout << setw(10) << "Name"; // right-padded to 10 chars cout << setfill('0') << setw(5) << 42; // 00042
Common Mistakes
- Forgetting
#include <iostream>—coutwon't be recognised. - Skipping
using namespace std;without prefixing —std::coutinstead, or both. endlin tight loops — flushes every line, slow for >10k iterations. Use"\n".- Mixing
printfandcout— sync the streams or use one consistently. - Forgetting
;— every statement ends with semicolon.
Interview Questions
Practice Exercises
- Profile — Print your name, age, and city on three lines. Hint: 3
coutlines. - Format a price — Print
$99.95with exactly 2 decimal places using<iomanip>. Hint:fixed << setprecision(2). - Aligned table — Print 3 rows with
setw(10)to left-pad names. Hint:setwfrom iomanip. - Raw string — Print a 5-line ASCII banner using a
R"(...)"literal. Hint: no escaping needed.
💡 Think Like a Programmer: Print early, print often. When debugging,
cout << "checkpoint A: x=" << x << "\n";saves hours. Add it, run it, delete it.
AI-powered recap
Quick recap quiz?
We'll generate 5 MCQs from this lesson and check your understanding instantly. Takes ~30 seconds.
# program
Program
C++
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Hello, Codekilla!\n";
cout << "Pi = " << fixed << setprecision(4) << 3.14159 << "\n";
return 0;
}Ready to move on?
// example library
Want more hands-on snippets in C++?
Browse 100 runnable examples · across 10 chapters · short, copy-paste-friendly · grouped by topic
// side-by-side reference
See this in other languages
Compare the same concept across C, C++, Java, and Python — one table, zero tab-switching.
// feedback.matters()
Did this lesson help you?
