Learn C++ โ 10 Examples
with Console Output
Each example below teaches one C++ concept. Read the code, press Run โ See Output, and the console output appears instantly. Copy any example with the copy button.
Hello, World!
Every programmer starts here. This program prints a message to the screen. It uses cout โ which stands for "console output" โ to display text.
๐ Teaches: Basic program structure, #include, main function, cout
1#include2using namespace std;34int main() {5 cout << "Hello, World!" << endl;6 return 0;7}
Variables and Data Types
Variables are containers that store values. C++ requires you to declare the type of each variable before using it โ int for whole numbers, double for decimals, string for text.
๐ Teaches: int, double, string, variable declaration, cout
1#include2#include3using namespace std;45int main() {6 int age = 20;7 double price = 9.99;8 string name = "Alice";910 cout << "Name: " << name << endl;11 cout << "Age: " << age << endl;12 cout << "Price: $" << price << endl;1314 return 0;15}
Getting User Input
cin reads input from the user (keyboard). The >> operator sends the input into your variable. This is the opposite of cout <<.
๐ Teaches: cin, >> operator, reading input, storing in variables
1#include2#include3using namespace std;45int main() {6 string name;7 int age;89 cout << "Enter your name: ";10 cin >> name;1112 cout << "Enter your age: ";13 cin >> age;1415 cout << "Hello, " << name << "!" << endl;16 cout << "You are " << age << " years old." << endl;1718 return 0;19}
If / Else Conditions
Conditions let your program make decisions. If a condition is true, one block of code runs. If it is false, another block runs instead.
๐ Teaches: if, else if, else, comparison operators, conditions
1#include2using namespace std;34int main() {5 int score = 75;67 if (score >= 90) {8 cout << "Grade: A" << endl;9 } else if (score >= 75) {10 cout << "Grade: B" << endl;11 } else if (score >= 60) {12 cout << "Grade: C" << endl;13 } else {14 cout << "Grade: F" << endl;15 }1617 return 0;18}
For Loop
A for loop repeats a block of code a set number of times. You set a starting value, a condition to keep looping, and how to update the counter each time.
๐ Teaches: for loop, counter variable, loop body, iteration
1#include2using namespace std;34int main() {5 // Print numbers 1 to 56 for (int i = 1; i <= 5; i++) {7 cout << "Count: " << i << endl;8 }910 cout << "Done!" << endl;11 return 0;12}
While Loop
A while loop keeps running as long as a condition is true. It is useful when you do not know in advance how many times to repeat.
๐ Teaches: while loop, condition, infinite loop prevention
1#include2using namespace std;34int main() {5 int number = 1;67 while (number <= 5) {8 cout << number << " x 2 = " << number * 2 << endl;9 number++; // increase by 1 each time10 }1112 return 0;13}
Functions
A function is a reusable block of code that does one specific job. You define it once and call it as many times as you need. Functions make your code organised and avoid repetition.
๐ Teaches: function definition, parameters, return type, calling functions
1#include2using namespace std;34// Function that adds two numbers5int add(int a, int b) {6 return a + b;7}89// Function that greets a person10void greet(string name) {11 cout << "Hello, " << name << "!" << endl;12}1314int main() {15 int result = add(10, 5);16 cout << "10 + 5 = " << result << endl;1718 greet("Bob");19 greet("Alice");2021 return 0;22}
Arrays
An array stores multiple values of the same type in one variable. You access each value using its index number, starting from 0.
๐ Teaches: array declaration, indexing from 0, array size, looping through arrays
1#include2using namespace std;34int main() {5 // Array of 5 scores6 int scores[5] = {88, 92, 75, 96, 81};78 cout << "All scores:" << endl;9 for (int i = 0; i < 5; i++) {10 cout << "Score " << i + 1 << ": " << scores[i] << endl;11 }1213 return 0;14}
Classes and Objects
A class is like a blueprint. An object is something built from that blueprint. Classes bundle together related data (attributes) and actions (methods) into one package โ this is the core idea of Object-Oriented Programming.
๐ Teaches: class, object, attributes, methods, constructor, OOP basics
1#include2#include3using namespace std;45class Dog {6public:7 string name;8 string breed;9 int age;1011 // Method โ an action the Dog can do12 void bark() {13 cout << name << " says: Woof!" << endl;14 }1516 void info() {17 cout << name << " is a " << breed;18 cout << " aged " << age << endl;19 }20};2122int main() {23 Dog myDog; // create an object24 myDog.name = "Rex";25 myDog.breed = "Labrador";26 myDog.age = 3;2728 myDog.info();29 myDog.bark();3031 return 0;32}
Simple Calculator
Putting it all together โ this program uses variables, conditions and functions to build a working calculator. It shows how the concepts from all previous examples combine into a real program.
๐ Teaches: switch statement, combining concepts, real program structure
1#include2using namespace std;34double calculate(double a, char op, double b) {5 if (op == '+') return a + b;6 if (op == '-') return a - b;7 if (op == '*') return a * b;8 if (op == '/') return a / b;9 return 0;10}1112int main() {13 double num1 = 20;14 double num2 = 4;1516 cout << num1 << " + " << num2 << " = ";17 cout << calculate(num1, '+', num2) << endl;1819 cout << num1 << " - " << num2 << " = ";20 cout << calculate(num1, '-', num2) << endl;2122 cout << num1 << " * " << num2 << " = ";23 cout << calculate(num1, '*', num2) << endl;2425 cout << num1 << " / " << num2 << " = ";26 cout << calculate(num1, '/', num2) << endl;2728 return 0;29}
Quick Reference
C++ Cheat Sheet
The most important C++ syntax at a glance. Bookmark this section.
#include <iostream>Include the input/output libraryusing namespace std;Use the standard namespace (saves typing std::)int main() { }Main function โ every program starts herecout << "text"Print text to the consolecin >> variableRead input from the keyboardendlEnd the line (like pressing Enter)int x = 5;Declare an integer variabledouble x = 3.14;Declare a decimal number variablestring s = "hello";Declare a text variableif (x > 0) { }Run code only if condition is truefor (int i=0; i<n; i++)Loop n timeswhile (condition) { }Loop while condition is trueint fn(int a) { }Define a function that returns intreturn 0;Exit main โ 0 means successclass Name { };Define a class (object blueprint)// commentSingle-line comment (ignored by compiler)