Skip to content

Beginner · First steps: compiling, output, variables and input · topic 2 of 42 · 20 min

Your first program: main, cout and namespaces

Explanation

Every C++ program starts running in a function called main. You print with std::cout and the << operator, and each statement ends with a semicolon. std:: means the name comes from the standard library's namespace.

The smallest useful program

cpp
#include <iostream>

int main() {
    std::cout << "Namaste, C++!\n";
    return 0;
}
Prints Namaste, C++! and a new line.

Let us read it line by line.

  • #include <iostream> brings in the input/output part of the standard library. The standard library is the large set of ready-made code that comes with every C++ compiler.
  • int main() starts the main function. A function is a named block of code. The operating system calls main when the program starts. int means main gives back a whole number.
  • The curly braces { } mark the body of main: the statements that run, top to bottom.
  • std::cout is the "character output" stream: text sent to it appears in the terminal. << means "send this into the stream".
  • "\n" is the newline character: it moves the cursor to the next line.
  • return 0; ends main and tells the operating system the program finished without error. Any other number usually means an error. (In main only, you may leave this line out; the compiler then returns 0 for you.)
  • Every statement ends with a semicolon ;. Forgetting it is the most common beginner error.

Chaining output

cpp
#include <iostream>

int main() {
    std::cout << "Train: " << 12951 << '\n';
    std::cout << "Fare: Rs " << 1450.50 << '\n';
    std::cout << 7 + 5 << '\n';
}
Prints Train: 12951, then Fare: Rs 1450.5 (cout drops trailing zeros by default), then 12.

You can chain many << in one statement. Text in double quotes is a string; numbers are printed as numbers, and expressions like 7 + 5 are calculated first. A single character uses single quotes, like '\n'.

std::endl versus '\n'

std::endl also ends the line, but it additionally flushes the stream: it forces the text out to the screen immediately. Flushing is slow when you print many lines, so prefer '\n' and use std::endl only when you really need the text shown at once (for example just before a long calculation).

Namespaces and std::

A namespace is a named group of names, so two libraries can both have something called "count" without a clash. Everything in the standard library lives in the namespace std. std::cout means "the cout that belongs to std". :: is called the scope resolution operator.

Think of it like this: Two students in your class are both called Rahul, so the teacher says "Rahul from Section A" and "Rahul from Section B". The section is the namespace; std::cout is "cout from the standard section".
cpp
#include <iostream>
using namespace std;   // fine in tiny practice files, avoid in real projects

int main() {
    cout << "No std:: needed here\n";
}
using namespace std; lets you drop std::, but it pulls hundreds of names into your file.
Careful: Never write using namespace std; in a header file (.h or .hpp). Every file that includes your header gets all of std dumped into it, which can cause confusing name clashes. In .cpp practice files it is common, and in competitive programming almost everyone uses it.

Comments

cpp
// A comment until the end of the line
/* A comment that can
   span many lines */
int main() { }
The compiler ignores comments. Use them to explain why, not what.

Reading compiler errors

Compiler messages look scary but always give a file name and line number, like hello.cpp:4:40: error: expected ';' before '}' token. Fix the FIRST error first; later errors are often caused by the first one. A missing semicolon is often reported on the next line.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Your first program: main, cout and namespaces · 1/6

Your first program

Let us write your first real C++ program.

Prefer a video by a teacher? Find free videos on “c++ hello world main cout explained beginners” on YouTube ↗

In real life: A railway ticket printout

Ticket machines at stations print a short summary: train number, class and fare. Under the hood the program sends text and numbers to an output stream, just like std::cout, only the stream goes to a printer instead of a screen.

cpp
#include <iostream>

int main() {
    std::cout << "PNR: 4521337890\n";
    std::cout << "Train 12951, Class 3A\n";
    std::cout << "Fare: Rs " << 2150 << '\n';
}
Prints three lines of a ticket.

Practice (0/3 done)

Task 1 · Question

What does this print? std::cout << "Sum: " << 4 + 6 << '\n';

Task 2 · Question

Which line has the bug? 1: #include <iostream> 2: int main() { 3: std::cout << "Hi" 4: }

Task 3 · Practice

Write a program that prints a small shop bill on four lines: the shop name, two items with prices, and the total (calculated with + in the code, not typed by hand).

Quick quiz

Question 1

1.Where does a C++ program start running?

Question 2

2.What does std:: in std::cout mean?

Question 3

3.Why is '\n' usually preferred over std::endl?

Question 4

4.Where should you never write using namespace std;?

Question 5

5.What does return 0; at the end of main mean?

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Where does a C++ program start running?

Answer: In the function main

The operating system calls main when the program starts.

What does std:: in std::cout mean?

Answer: cout comes from the std namespace

std is the namespace of the standard library and :: picks a name from it.

Why is '\n' usually preferred over std::endl?

Answer: '\n' does not flush the stream, so it is faster

std::endl ends the line and flushes the output, which costs time when printing many lines.

Where should you never write using namespace std;?

Answer: In a header file

In a header it leaks into every file that includes the header and can cause name clashes.

What does return 0; at the end of main mean?

Answer: The program finished successfully

The value returned from main is the exit code. 0 means success.

std::cout << std::setw(5) << 42; prints…Related

Answer: 42 (3 spaces then 42)

setw(5) pads the next value to 5 characters, on the left by default.

From Reading input and formatting output

Where does every C program start executing?Related

Answer: The main function

main is the entry point.

From The structure of a C program

Why is std::string_view a good parameter type for read-only text?Related

Answer: It accepts std::string, literals and substrings without copying

A view is just a pointer and a length.

From std::optional, std::variant and std::string_view

What ends a statement in C#?Related

Answer: A semicolon ;

Every C# statement ends with a semicolon.

From Your first program: output, input and the Main method

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “First steps: compiling, output, variables and input” before its exam: Variables, types and constants, Reading input and formatting output.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.

← Previous: What C++ is and how compiling works