Your First C++ Program: Hello World

The classic first program prints a message on the screen.

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
Output

Hello, World!

Understand every line

CodeMeaning
#include <iostream>Adds the input and output library, so we can use std::cout
int main()The starting point. Every C++ program has one main
{ }A block of code
std::coutThe standard output stream (the screen). std:: means it is in the std namespace
<<The insertion operator: sends the text to the stream
std::endlA new line, and it also flushes the output
return 0;Tells the system that the program ended well. In main it is optional

Newline: \n or std::endl

#include <iostream>

int main() {
    std::cout << "First line\n";
    std::cout << "Second line" << std::endl;
    std::cout << "Tab:\tdone\n";
}
Output

First line
Second line
Tab: done

'\n' is faster. std::endl also flushes the buffer, which is slow if you do it many times.

The new way: std::print (C++23)

C++23 has std::print and std::println, which are easy and use the same format as std::format:

#include <print>

int main() {
    std::println("Hello, {}!", "World");
    std::println("{} + {} = {}", 2, 3, 2 + 3);
}
Output

Hello, World!
2 + 3 = 5

Your compiler must support it (GCC 14 or newer, recent Clang and MSVC).

What if there is a mistake?

#include <iostream>

int main() {
    std::cout << "Hello"
    return 0;
}
Output

Oops.cpp: In function 'int main()':
Oops.cpp:4:25: error: expected ';' before 'return'
4 | std::cout << "Hello"
| ^
| ;
5 | return 0;
| ~~~~~~

Read the error from the top. It shows the file, the line and what is expected.

Common beginner mistakes

  • A missing semicolon ; at the end of a statement.
  • Forgetting #include <iostream>.
  • Writing cout without std:: (or without using namespace std;).
  • Using >> for output or << for input.
Note: In real projects, avoid using namespace std; in header files. It can cause name clashes. Next: C++ Syntax.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.