Your First C++ Program
Now that your compiler works, it is time to write a real program and understand every line of it. You will learn the structure every C++ program shares, two ways to print output (the modern std::println from C++23 and the classic std::cout), how to write comments, and how to read the compiler's error messages without panic.
The structure of a C++ program
Create a file called welcome.cpp and type this program. Type it rather than copy it: your fingers learn the syntax faster that way.
// welcome.cpp: my first C++ program
#include <print>
int main() {
std::println("Welcome to C++, Priya!");
std::println("Today we learn to print.");
return 0;
}Welcome to C++, Priya! Today we learn to print.
Line by line:
// welcome.cpp ...is a comment. The compiler ignores everything after//on that line.#include <print>tells the preprocessor to bring in the standard library header that declaresstd::println. A header is a file of declarations you can reuse.int main()defines the main function. Every C++ program starts running at the first line insidemain. Theintmeansmainreturns a whole number to the operating system.- The curly braces
{and}mark the start and end of the function body. std::println("...");is a statement that prints text and then a newline.stdis the namespace of the standard library, and::means "the name inside". Every statement ends with a semicolon.return 0;tells the operating system the program finished successfully. Inmainonly, you may leave it out; the compiler then behaves as if you wrotereturn 0;.
Compile and run it as you learned in Install a Compiler & VS Code:
g++ -std=c++23 -Wall -Wextra welcome.cpp -o welcome
./welcomeprint, println and placeholders
C++23 gives you two printing functions in <print>:
std::printlnprints and then moves to a new line.std::printprints and stays on the same line.
Both understand placeholders. Each {} in the text is replaced by the next value you pass. You can also number the placeholders, starting from 0, to choose the order yourself.
#include <print>
int main() {
std::print("Train 12015 ");
std::print("leaves at ");
std::println("{}:{} am", 6, 10);
std::println("Fare for {} seats: Rs. {}", 3, 3 * 450);
std::println("{1} comes before {0}", "second", "first");
}Train 12015 leaves at 6:10 am Fare for 3 seats: Rs. 1350 first comes before second
The two std::print calls do not add newlines, so the first three calls build one line together. In the last line, {1} takes the second value and {0} the first. You will learn many more formatting options, such as decimal places and alignment, in Strings, string_view & format.
The classic way: std::cout
Before C++23, every C++ program printed with std::cout (pronounced "see-out", short for character output) from the <iostream> header. You will see it in almost all existing code, books and exam papers, so you must be able to read it.
#include <iostream>
int main() {
int seats = 3;
std::cout << "Fare for " << seats << " seats: Rs. " << seats * 450 << '\n';
std::cout << "Have a safe journey!" << std::endl;
}Fare for 3 seats: Rs. 1350 Have a safe journey!
The << operator sends each piece to the output, one after another. '\n' is the newline character. std::endl also prints a newline but then flushes the output (forces it to be written immediately), which is slower when you print many lines. Prefer '\n'.
Comments and special characters
C++ has two kinds of comments. Use them to explain why code does something, not to repeat what it obviously does.
#include <print>
/* A block comment can span
several lines. */
int main() {
std::println("Name:\tRohan"); // \t inserts a tab
std::println("He said \"Well played!\""); // \" prints a double quote
std::println("Path: C:\\cpp\\notes"); // \\ prints one backslash
std::println("Set {{1, 2, 3}} has {} items", 3);
}Name: Rohan
He said "Well played!"
Path: C:\cpp\notes
Set {1, 2, 3} has 3 itemsA backslash starts an escape sequence: \n (newline), \t (tab), \" (double quote) and \\ (backslash). Inside std::println text, curly braces are special, so you write {{ and }} to print a literal { or }.
Reading compiler errors
Everyone makes typing mistakes. Here a semicolon is missing at the end of the first statement:
#include <print>
int main() {
std::println("Score: {}", 42)
std::println("Done");
}GCC stops and prints an error similar to this:
error.cpp: In function 'int main()': error.cpp:4:34: error: expected ';' before 'std'
The message gives the file name, the line number (4) and the column (34), then describes the problem. Go to that line and look at the end of it. Two tips: always fix the first error first, because one mistake can cause several later messages, and read the line just before the reported one as well.
Common mistakes
- Missing semicolons. Every statement ends with
;. The error often points to the next line. - Wrong capital letters. C++ is case-sensitive:
Main,STD::printlnandstd::PrintLnare all errors. - Forgetting the header. Using
std::printlnwithout#include <print>gives an error such as "'println' is not a member of 'std'". - Single quotes for text.
'Hello'is wrong; text uses double quotes"Hello". Single quotes hold exactly one character, such as'A'.
Key points
- Every program has an
int main()function where execution starts; statements end with;. #includebrings in standard library headers such as<print>and<iostream>.std::printlnprints with a newline,std::printwithout;{}placeholders are filled with values.std::cout << ... << '\n'is the classic way to print and is still everywhere in existing code.- Use
//and/* */for comments,\n,\t,\"and\\for special characters, and{{}}for literal braces instd::println. - Read compiler errors from the first one, using the line and column numbers.
Exercise
Write a program that prints a small cricket scorecard for Ananya: her name on the first line, then Runs: 58 and Balls: 41 on separate lines using placeholders, and finally a line Strike rate is runs * 100 / balls exactly as written. Then rewrite the first two lines using std::cout.
Show solution
#include <iostream>
#include <print>
int main() {
std::println("Player: {}", "Ananya");
std::println("Runs: {}", 58);
std::println("Balls: {}", 41);
std::println("Strike rate is runs * 100 / balls");
std::cout << "Player: " << "Ananya" << '\n';
std::cout << "Runs: " << 58 << '\n';
}Player: Ananya Runs: 58 Balls: 41 Strike rate is runs * 100 / balls Player: Ananya Runs: 58
The text inside quotes is printed exactly, so the * and / in the last std::println line are just characters, not maths.
Quick Quiz
1. Where does a C++ program start running?
The operating system calls main, so execution starts inside it.
2. What is the difference between std::print and std::println?
Both format text the same way; only println moves to a new line at the end.
3. What does std::println("{1}-{0}", "a", "b"); print?
Numbered placeholders choose values by position: {1} is "b" and {0} is "a".
4. Why is '\n' usually preferred over std::endl?
Both end the line, but the extra flush of std::endl costs time when printing a lot.
Learn C++ with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
