C++ โ Complete Beginner Tutorial
6 modules ยท 20 examples ยท Click โถ Run Program to see the console output
๐ก How to use this tutorial
Read each explanation, study the code, then click โถ Run Program to see the output.
Your First C++ Program
Every C++ program starts from the same skeleton. You need to include libraries (like iostream for input/output), then write a main() function โ this is where your program begins running. Every line of code ends with a semicolon (;). We use cout to print text to the screen and endl to move to the next line.
Hello World โ Your Very First Program
This is the simplest C++ program possible. It prints one line of text to the console. Read through each line โ the comment explains exactly what it does. In C++, comments start with // and are ignored by the computer.
#include <iostream> // Lets us use cout and cin
using namespace std; // So we don't have to type std::cout
int main() { // Every program starts here
cout << "Hello, World!" << endl;
return 0; // 0 means the program finished OK
}#include <iostream> loads the input/output library. Without it, cout does not exist. Think of it like importing a toolbox before you start building.
Printing Multiple Lines
You can use cout as many times as you want. The << symbol means "send this text to the console". endl moves the cursor to the next line. \n inside a string does the same thing as endl but slightly faster.
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++!" << endl;
cout << "This is line two." << endl;
cout << "And this is line three." << endl;
// \n also creates a new line (inside the string)
cout << "Line A\nLine B\nLine C" << endl;
return 0;
}cout << "text" << endl; is the C++ equivalent of print() in Python or System.out.println() in Java. You will type this thousands of times โ get comfortable with it!
Comments โ Explaining Your Code
Comments are notes you leave in your code for yourself (and others). The computer completely ignores them. Single-line comments start with //. Multi-line comments go between /* and */. Good comments explain WHY you wrote something, not just what it does.
#include <iostream>
using namespace std;
int main() {
// This is a single-line comment
cout << "Line 1" << endl;
/*
This is a multi-line comment.
It can span as many lines as you need.
Use it to explain bigger sections of code.
*/
cout << "Line 2" << endl;
cout << "Line 3" << endl; // Comment at end of line
return 0;
}Get into the habit of writing comments as you code, not after. Future-you will be very grateful when you come back to read your own code six months later.
Variables & Data Types
A variable is a named box that stores a value. In C++ you must tell the computer what TYPE of data the box will hold before you use it โ this is called static typing. The main types are: int (whole numbers), double (decimal numbers), string (text), and bool (true/false). Once you declare a variable, you can change its value as many times as you like.
Declaring and Using Variables
To create a variable, write the type, then the name, then optionally = value. You must include <string> to use strings. Variable names are case-sensitive โ age and Age are different variables. Choose names that describe what the variable holds.
#include <iostream>
#include <string> // Needed for string type
using namespace std;
int main() {
// int = whole numbers (no decimals)
int age = 16;
int score = 95;
// double = numbers with decimals
double price = 29.99;
double temperature = -5.5;
// string = text (always use double quotes)
string name = "Alice";
string city = "Cape Town";
// bool = true or false only
bool isStudent = true;
bool hasJob = false;
// Print them all
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "City: " << city << endl;
cout << "Score: " << score << endl;
cout << "Price: R" << price << endl;
cout << "Temp: " << temperature << "ยฐC" << endl;
cout << "Is student: " << isStudent << endl;
return 0;
}bool prints as 1 (true) or 0 (false) by default in C++. This is normal! The number 1 means true and 0 means false in C++ โ this comes from the way computers work at the hardware level.
Maths with Variables
C++ uses the same maths operators you know: + (add), - (subtract), * (multiply), / (divide), % (modulo โ the remainder after division). Integer division drops the decimal โ 7 / 2 gives 3, not 3.5. Use double if you need decimals.
#include <iostream>
using namespace std;
int main() {
int a = 20;
int b = 7;
cout << "a + b = " << (a + b) << endl; // 27
cout << "a - b = " << (a - b) << endl; // 13
cout << "a * b = " << (a * b) << endl; // 140
cout << "a / b = " << (a / b) << endl; // 2 (int!)
cout << "a % b = " << (a % b) << endl; // 6 (remainder)
// Use double for decimal division
double x = 20.0;
double y = 7.0;
cout << "20.0 / 7.0 = " << (x / y) << endl;
// Shortcut operators
int count = 0;
count++; // count = count + 1
count += 5; // count = count + 5
count *= 2; // count = count * 2
cout << "count = " << count << endl;
return 0;
}The % operator (modulo) is more useful than it looks. "Is this number even?" โ use n % 2 == 0. "Did I finish a full hour?" โ use minutes % 60. You will use it constantly once you start solving real problems.
Getting Input from the User
cin reads what the user types. The >> symbol means "read from the keyboard into this variable". After the user types something and presses Enter, the value is stored in your variable. For reading a full line with spaces, use getline() instead of cin.
#include <iostream>
#include <string>
using namespace std;
int main() {
// Read a number
int age;
cout << "Enter your age: ";
cin >> age;
cout << "You are " << age << " years old." << endl;
// Read a word (stops at space)
string firstName;
cout << "Enter your first name: ";
cin >> firstName;
// Read a full line (including spaces)
string fullName;
cin.ignore(); // Clear leftover newline
cout << "Enter your full name: ";
getline(cin, fullName);
cout << "Hello, " << fullName << "!" << endl;
return 0;
}cin stops reading at a space. So "Alice Smith" with cin gives you only "Alice". Use getline(cin, variable) when the input might contain spaces โ like a full name, address, or sentence.
Conditions โ Making Decisions
Programs need to make decisions. If this condition is true, do one thing โ otherwise do something else. In C++, you use if, else if, and else for this. The condition goes inside parentheses and must produce a true or false result. Comparison operators: == (equal), != (not equal), > (greater), < (less), >= (greater or equal), <= (less or equal).
if / else if / else
The if statement checks a condition. If it is true, the code inside the curly braces {} runs. If it is false, the else block runs instead. You can chain multiple conditions with else if. Only ONE block ever runs โ the first one where the condition is true.
#include <iostream>
using namespace std;
int main() {
int score = 75;
if (score >= 80) {
cout << "Grade: A โ Excellent!" << endl;
} else if (score >= 70) {
cout << "Grade: B โ Good job!" << endl;
} else if (score >= 60) {
cout << "Grade: C โ Average" << endl;
} else if (score >= 50) {
cout << "Grade: D โ Just passed" << endl;
} else {
cout << "Grade: F โ Try again" << endl;
}
// Check if a number is even or odd
int number = 42;
if (number % 2 == 0) {
cout << number << " is even" << endl;
} else {
cout << number << " is odd" << endl;
}
return 0;
}Always use == (double equals) to compare values. A single = is assignment โ it sets a value. if (x = 5) does not check if x equals 5, it SETS x to 5. This is a very common beginner mistake.
AND, OR, NOT โ Combining Conditions
You can combine conditions: && means AND (both must be true), || means OR (at least one must be true), ! means NOT (flips true to false). Use parentheses to group conditions when combining them โ it makes your code clearer and avoids unexpected results.
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 17;
bool hasID = true;
// && (AND) โ both conditions must be true
if (age >= 18 && hasID) {
cout << "Entry allowed" << endl;
} else {
cout << "Entry denied" << endl;
}
// || (OR) โ at least one must be true
string city = "Cape Town";
if (city == "Cape Town" || city == "Durban") {
cout << city << " is a coastal city" << endl;
}
// ! (NOT) โ flips the condition
bool isRaining = false;
if (!isRaining) {
cout << "Good weather for a walk!" << endl;
}
// Combining AND + OR with parentheses
int marks = 82;
bool attended = true;
if ((marks >= 80) && attended) {
cout << "Distinction achieved!" << endl;
}
return 0;
}&& has higher priority than ||, just like * is higher than + in maths. So a || b && c is read as a || (b && c). When in doubt, always use parentheses to make your intent clear.
switch โ Matching Multiple Values
A switch statement is a cleaner way to write many if/else if branches when you are comparing ONE variable against multiple fixed values. Each case ends with break โ without break, the code falls through into the next case. The default case runs if no case matched.
#include <iostream>
using namespace std;
int main() {
int day = 3; // 1=Monday, 2=Tuesday, etc.
switch (day) {
case 1:
cout << "Monday โ start of the week" << endl;
break;
case 2:
cout << "Tuesday โ keep going!" << endl;
break;
case 3:
cout << "Wednesday โ midweek!" << endl;
break;
case 4:
cout << "Thursday โ almost Friday" << endl;
break;
case 5:
cout << "Friday โ last day of school!" << endl;
break;
case 6:
case 7:
cout << "Weekend โ relax!" << endl;
break;
default:
cout << "Invalid day number" << endl;
}
return 0;
}Notice that case 6 and case 7 share the same block โ this is called fall-through and is intentional here. If you forget break in other cases by accident, the program runs the NEXT case too, which is usually a bug.
Loops โ Repeating Actions
Loops let you run the same code many times without writing it over and over. There are three types of loops in C++: the for loop (when you know how many times to repeat), the while loop (when you repeat until a condition is false), and the do-while loop (runs at least once, then checks). break exits a loop early. continue skips the rest of the current iteration and goes to the next one.
The for Loop
The for loop has three parts inside the parentheses: (1) start โ set up a counter variable, (2) condition โ keep looping while this is true, (3) update โ change the counter each time. These three parts together control exactly how many times the loop runs.
#include <iostream>
using namespace std;
int main() {
// Count from 1 to 5
cout << "Counting up:" << endl;
for (int i = 1; i <= 5; i++) {
cout << " i = " << i << endl;
}
// Count down from 5 to 1
cout << "Counting down:" << endl;
for (int i = 5; i >= 1; i--) {
cout << " " << i << "..." << endl;
}
cout << " Blast off!" << endl;
// Count by twos (even numbers)
cout << "Even numbers:" << endl;
for (int i = 2; i <= 10; i += 2) {
cout << i << " ";
}
cout << endl;
// Calculate a total using a loop
int total = 0;
for (int i = 1; i <= 10; i++) {
total += i;
}
cout << "1+2+...+10 = " << total << endl;
return 0;
}i++ is shorthand for i = i + 1. i-- subtracts 1. i += 2 adds 2. The counter variable (usually named i, j, or k) only exists inside the loop โ you cannot use it after the closing brace.
The while Loop
A while loop keeps running as long as the condition in the parentheses is true. It checks the condition BEFORE each run. If the condition is false from the start, the loop body never runs at all. Be careful โ if the condition never becomes false, you get an infinite loop!
#include <iostream>
using namespace std;
int main() {
// Basic while loop
int count = 1;
while (count <= 5) {
cout << "Count: " << count << endl;
count++; // IMPORTANT: update count or loop never ends!
}
// Validate user input (keep asking until valid)
int number = -1;
cout << "Enter a number between 1 and 10: ";
// (In this demo, we simulate input of 7)
number = 7; // Simulated input
while (number < 1 || number > 10) {
cout << "Invalid! Try again: ";
number = 5; // Would be cin >> number in real code
}
cout << "You entered: " << number << endl;
// Guessing game style countdown
int lives = 3;
while (lives > 0) {
cout << "Lives remaining: " << lives << endl;
lives--;
}
cout << "Game Over!" << endl;
return 0;
}The most common while loop mistake is forgetting to update the variable inside the loop. If count never increases, the condition count <= 5 is ALWAYS true and your program freezes in an infinite loop.
break and continue
break immediately exits the loop โ the rest of the loop body is skipped and the program continues after the closing brace. continue skips the rest of the CURRENT iteration only โ the loop keeps running from the next iteration. Both work in for and while loops.
#include <iostream>
using namespace std;
int main() {
// break โ stop the loop early
cout << "Loop with break (stop at 4):" << endl;
for (int i = 1; i <= 10; i++) {
if (i == 4) {
cout << " Found 4 โ stopping!" << endl;
break; // Exit the loop now
}
cout << " i = " << i << endl;
}
// continue โ skip one iteration
cout << "Loop with continue (skip odd numbers):" << endl;
for (int i = 1; i <= 8; i++) {
if (i % 2 != 0) {
continue; // Skip to next iteration
}
cout << " Even: " << i << endl;
}
return 0;
}Think of break as an emergency exit from the loop. Think of continue as "skip this one and move on". Both are useful โ break is great for search operations (stop when you find what you need), continue is great for filtering (skip unwanted items).
Functions โ Reusable Blocks
A function is a named block of code that you can run any time by "calling" its name. Functions help you avoid repeating the same code. You write the function once and call it many times. In C++, you declare the return type before the function name. Use void if the function does not return anything. In C++, functions must be defined BEFORE the line that calls them โ or you need a "forward declaration" at the top.
Defining and Calling Functions
A function definition has four parts: the return type, the function name, the parameters in parentheses, and the body in curly braces. You call a function by writing its name followed by (). If the function has parameters, you pass the values inside the parentheses.
#include <iostream>
#include <string>
using namespace std;
// Function with no parameters, returns nothing (void)
void sayHello() {
cout << "Hello there!" << endl;
}
// Function with one parameter
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
// Function with two parameters that returns an int
int add(int a, int b) {
return a + b;
}
// Function that returns a string
string getGrade(int score) {
if (score >= 80) return "A";
if (score >= 70) return "B";
if (score >= 60) return "C";
return "F";
}
int main() {
sayHello(); // Call with no arguments
greet("Alice"); // Call with one argument
greet("Bob");
int result = add(15, 27);
cout << "15 + 27 = " << result << endl;
cout << "Score 85 = Grade " << getGrade(85) << endl;
cout << "Score 65 = Grade " << getGrade(65) << endl;
return 0;
}The return type must match what you actually return. If you say the function returns int, you must have return someNumber; inside. void functions do not need a return statement (or you can write return; with nothing after it).
Practical Function Examples
Here are some practical functions you might write in real programs โ calculating areas, finding the larger of two numbers, and checking if a number is even. These show how functions make code cleaner and more reusable.
#include <iostream>
using namespace std;
// Calculate area of a rectangle
double rectangleArea(double width, double height) {
return width * height;
}
// Return the larger of two numbers
int maximum(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Check if a number is even
bool isEven(int n) {
return (n % 2 == 0);
}
// Print a decorative line
void printLine(int length) {
for (int i = 0; i < length; i++) {
cout << "-";
}
cout << endl;
}
int main() {
printLine(30);
cout << "Rectangle 5x3: " << rectangleArea(5, 3) << endl;
cout << "Rectangle 10x2.5: " << rectangleArea(10, 2.5) << endl;
printLine(30);
cout << "Max of 14, 27: " << maximum(14, 27) << endl;
cout << "Max of 99, 50: " << maximum(99, 50) << endl;
cout << "Is 8 even? " << (isEven(8) ? "Yes" : "No") << endl;
cout << "Is 7 even? " << (isEven(7) ? "Yes" : "No") << endl;
return 0;
}A function should do ONE thing and do it well. If your function is getting long and complicated, split it into smaller functions. This is called the "Single Responsibility Principle" and it is one of the most important ideas in programming.
Arrays & Vectors
An array stores multiple values of the SAME type in one variable. Instead of making 10 separate variables, you make one array that holds 10 values. Each value has an index starting from 0 (not 1!). Arrays have a fixed size. Vectors are like arrays but they can grow and shrink dynamically โ they are almost always the better choice in modern C++.
Arrays โ Fixed Size Lists
Declare an array by writing the type, the name, and the size in square brackets. Access individual elements using their index โ remember, the first element is index 0, not 1. The last element of an array of size n is at index n-1.
#include <iostream>
using namespace std;
int main() {
// Declare and initialise an array of 5 ints
int scores[5] = {95, 82, 78, 91, 67};
// Access individual elements (index starts at 0!)
cout << "First score: " << scores[0] << endl;
cout << "Second score: " << scores[1] << endl;
cout << "Last score: " << scores[4] << endl;
// Loop through ALL elements
cout << "All scores: ";
for (int i = 0; i < 5; i++) {
cout << scores[i] << " ";
}
cout << endl;
// Find the highest score
int highest = scores[0];
for (int i = 1; i < 5; i++) {
if (scores[i] > highest) {
highest = scores[i];
}
}
cout << "Highest score: " << highest << endl;
// Calculate the average
int total = 0;
for (int i = 0; i < 5; i++) {
total += scores[i];
}
double average = (double)total / 5;
cout << "Average score: " << average << endl;
return 0;
}The most common array mistake is going out of bounds โ accessing scores[5] when the array only has indices 0โ4. C++ does NOT warn you about this. It silently reads garbage memory, causing weird bugs. Always double-check your loop condition.
Vectors โ Dynamic Lists (Better than Arrays)
Vectors are like arrays but smarter. They live in the <vector> library. You can add items with push_back(), remove the last item with pop_back(), and check the size with .size(). The range-based for loop (for auto x : vec) is the cleanest way to loop through a vector.
#include <iostream>
#include <vector> // Needed for vector
#include <string>
using namespace std;
int main() {
// Create an empty vector of strings
vector<string> names;
// Add items with push_back()
names.push_back("Alice");
names.push_back("Bob");
names.push_back("Charlie");
names.push_back("Diana");
// How many items?
cout << "Number of names: " << names.size() << endl;
// Access by index (same as array)
cout << "First: " << names[0] << endl;
cout << "Last: " << names[names.size()-1] << endl;
// Range-based for loop (cleanest way!)
cout << "All names:" << endl;
for (string name : names) {
cout << " - " << name << endl;
}
// Remove the last item
names.pop_back();
cout << "After removing last: " << names.size() << " names" << endl;
// Vector of numbers
vector<int> nums = {10, 20, 30, 40, 50};
int sum = 0;
for (int n : nums) {
sum += n;
}
cout << "Sum of nums: " << sum << endl;
return 0;
}In modern C++, prefer vector over raw arrays almost always. Vectors are safer (they know their own size), more flexible (they can grow), and just as fast for most uses. Raw arrays are mainly used when you need to interface with old C code or work at the hardware level.
You finished the C++ tutorial!
You can now write C++ programs with variables, conditions, loops, functions, arrays and vectors. These are the fundamentals used in games, systems software, and high-performance applications worldwide.