C++ basics: a hands-on first tutorial
New to C++, or to programming entirely? Good — this is written for you. We start from “what even is C++” and finish with a small program you compile and run yourself, one patient step at a time.
C++ is a language where you tell the computer exactly what to do, then compile your code into a program the machine runs directly. It powers browsers, games, operating systems, and the high-performance guts of almost everything fast. Bjarne Stroustrup created C++ in the early 1980s as an extension of C, adding classes so that code could be organised around objects — which is where the “++” comes from (it's the C increment operator: “C, and then some”).1 This tutorial assumes you know nothing about C++. Every new idea comes with a tiny, runnable example, and every language feature links to a reputable source — cppreference.com2, the C++ Core Guidelines3, and learncpp.com4 — so you can always read the authoritative version.
You don't need to memorise anything. Read a section, type the example yourself (typing beats copy-pasting when you're learning), watch what happens, then move on. Let's begin.
01What C++ is, in one minute
C++ is a compiled language. That's the big idea, and it's worth sitting with. With an interpreted language, a separate program reads your code line by line as it runs. With C++, you run a compiler — a tool like GCC, Clang, or MSVC — that translates your whole program into machine code before you run it. The result is a standalone executable: fast, and independent of the language tools.5 That compile-ahead step is exactly why C++ is the choice for things where speed and control matter.
Two terms you'll meet immediately:
-
Source file — the plain-text file you write, traditionally named
with a
.cppextension. -
Compiler — the program that turns your
.cppinto an executable. On most systems the standard command-line compilers areg++(GCC) orclang++(Clang).6
02Install a compiler
You need a C++ compiler before any code will run. Which one depends on your system:
-
Linux — install the GNU compiler collection. On Debian/Ubuntu:
sudo apt install g++. Theg++command then compiles C++.6 -
macOS — install the Xcode command-line tools with
xcode-select --install; that providesclang++. - Windows — the friendliest path is learncpp.com's walkthrough, which recommends Visual Studio (with the “Desktop development with C++” workload) or MinGW-w64 / Clang.4 The MSVC compiler ships inside Visual Studio.
Verify it works by opening a terminal and running g++ --version (or
clang++ --version). If it prints a version number, you're set. The current
ISO standard is C++20, with C++23 published and compilers rolling out support — but
everything in this tutorial works on any reasonably modern compiler.7
03Your first program
Here is the smallest interesting C++ program. Don't worry that it looks dense — we'll take it apart line by line.
#include <iostream>
int main() {
std::cout << "Hello, world!";
return 0;
}
Save it as hello.cpp, then compile and run:
# compile
g++ hello.cpp -o hello
# run
./hello
That prints Hello, world!. Now the line-by-line:
-
#include <iostream>pulls in the standard input/output stream library, which definesstd::cout(the screen) andstd::cin(the keyboard). The preprocessor inserts that library's declarations before compiling.8 -
int main()definesmain— the function every C++ program must have. Execution starts here.intmeans it returns an integer.9 -
std::cout << "Hello, world!";sends the text to the screen. The<<is the stream insertion operator: “push this into the output stream.”10 -
return 0;endsmainand tells the operating system the program finished successfully. By convention,0means “all good.”9 -
Every statement ends with a semicolon
;. In C++, the semicolon is the full stop of a command — forget it and the compiler will complain.11
04Variables and types
In C++ you must declare a variable's type when you create it. The type tells the compiler how much memory to set aside and what operations are allowed. Unlike Python, types are fixed at compile time — this is what “statically typed” means, and it's a big reason C++ is fast and catches whole classes of bugs early.12
The everyday built-in types:
int age = 30; // whole numbers
double price = 9.99; // decimals (double-precision float)
float ratio = 0.5f; // decimals (single-precision)
bool open = true; // true / false
char letter= 'A'; // a single character
std::string name = "Ada"; // a sequence of characters
A few things worth noticing:
-
intis the workhorse integer type;doubleis the usual floating-point type. The Core Guidelines suggest preferringdoubleoverfloatunless you have a space reason not to.3 -
std::stringlives in<string>, so you'd add#include <string>to use it.13 -
Modern C++ (C++11 and later) lets you write
auto count = 0;and let the compiler deduce the type — but for learning, naming the type explicitly keeps things clear.14
You can change a variable's value later by assigning again, but you can't change its type:
age = 31; // fine
// age = "thirty"; // error: age is an int, not text
05Output and input: cout and cin
You've met std::cout for output. You can chain several
<< to build a line, and end with std::endl (or
"\n") to drop to a new line.10
std::cout << "You are " << age << " years old." << std::endl;
For input, use std::cin with the extraction operator
>>. Whatever the user types flows into your variable:
int year;
std::cout << "Birth year: ";
std::cin >> year; // reads an integer from the keyboard
std::cout << "Approx age: " << (2026 - year) << std::endl;
One gotcha for later: std::cin >> year reads a number, but if the user
types letters it goes wrong. Real programs check input — we'll handle that properly
in Part 2 (intermediate).
06Doing maths
The arithmetic operators are what you'd expect: + -
* /, plus % (modulo — the remainder after
division).15
int a = 17, b = 5;
std::cout << (a + b) << " " // 22
<< (a / b) << " " // 3 (integer division drops the fraction)
<< (a % b) << std::endl; // 2 (remainder)
Watch the integer-division trap: 17 / 5 is 3, not
3.4, because both numbers are int. To get the decimal, make at
least one a double: 17.0 / 5 → 3.4.
07Making decisions with if
A program that can't choose isn't much of a program. The if statement runs a
block only when a condition is true. Conditions use comparison operators:
== (equal — note the double equals), != (not equal), and
< > <= >=.16
if (age >= 18) {
std::cout << "You can vote." << std::endl;
} else {
std::cout << "Not yet." << std::endl;
}
Curly braces { } mark a block. For a single statement you can omit them, but
keeping the braces is a habit the Core Guidelines explicitly recommend — it prevents
the classic “I added a line and it silently fell outside the if” bug.3
You can chain alternatives with else if.
08Repeating with loops
Computers are brilliant at repetition, and C++ gives you two main loops. A
for loop repeats a known number of times; a while loop repeats
as long as a condition holds.17
// count 1 to 5
for (int i = 1; i <= 5; i = i + 1) {
std::cout << i << " ";
}
The for header reads almost like English: start i at 1; keep
going while i <= 5; each turn add 1 to i. A
while loop is better when you don't know the count up front — say,
“keep asking until the answer is right.”
int n = 0;
while (n < 3) {
std::cout << "n is " << n << std::endl;
n = n + 1;
}
09Grouping code into functions
When you find yourself writing the same few lines again and again, wrap them in a
function — a named, reusable block. You've already used one
(main); now write your own with the int/void return
type, the name, and parentheses.18
int square(int x) {
return x * x;
}
// later, in main:
std::cout << square(4) << std::endl; // prints 16
square takes an int called x and
returns its square. Functions make programs readable and testable: each piece
does one job, and you can reason about it in isolation. The Core Guidelines put it plainly
— “organise programs around functions and interfaces,” and keep
functions small and focused.3
10A first small project: a number-guessing game
Let's combine everything into a real, runnable program. The computer picks a number; the player guesses; it says “too high” or “too low” until they win. We'll use a simple pseudo-random number (a fuller version with proper seeding comes in Part 2).
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
int main() {
std::srand(time(nullptr)); // seed the generator
int secret = std::rand() % 20 + 1; // 1..20
int guess, tries = 0;
std::cout << "I'm thinking of a number from 1 to 20.\n";
while (true) {
std::cout << "Your guess: ";
std::cin >> guess;
tries = tries + 1;
if (guess < secret) std::cout << "Too low.\n";
else if (guess > secret) std::cout << "Too high.\n";
else {
std::cout << "Correct in " << tries << " tries!\n";
break; // leave the loop
}
}
return 0;
}
Read it slowly and you'll recognise every piece: #include for the libraries,
main, variables with types, std::cin/std::cout,
if/else if/else, a while (true) loop
ended by break, and return 0. That's a genuine, interactive
program — and you now understand every line of it.
std::rand(), which is simple but low-quality and
now discouraged for serious use. C++11 introduced <random> with proper
engines like std::mt19937. We'll switch to it in Part 2 — for a first
project, rand() keeps the focus on the logic.19
11Where to go next
You've covered the true fundamentals: compiling, variables and types, input/output, arithmetic, decisions, loops, and functions. That's most of what any C++ program is built from. Everything else — the standard library, classes, memory, templates — is more of the same, plus powerful new ideas.
- Practise more than you read. Programming is a skill like an instrument; understanding a chord isn't the same as playing one. Retype the examples, break them on purpose, and fix them.
- Work the reputable tutorials next. learncpp.com is a free, modern, and widely recommended C++ course.4 The C++ Core Guidelines are the community's agreed best practices, maintained by Bjarne Stroustrup and Herb Sutter.3
- Keep a reference open. When you forget a detail, cppreference.com is the definitive C++ reference — dense, but authoritative.2
- Write readable code. The Core Guidelines' spirit is simple: code is read far more often than it's written. Small functions, clear names, braces on every block.
Everyone who writes C++ fluently once stared at their first Hello, world! and
a wall of compiler errors. The distance from here to there is just practice — and
you've already taken the first steps.