Skip to main content

Command Palette

Search for a command to run...

C++ for Absolute Beginners: Learn by Building Simple Programs

Updated
16 min readView as Markdown

Have you ever wondered how a computer knows what to do?

A computer is powerful, but it cannot think like a human. It follows instructions. Programming is the process of writing those instructions, and C++ is one of the languages we can use to communicate with a computer.

In this article, we will learn C++ step by step using simple explanations, relatable examples, and small programs.


1. What Is C++?

C++ is a general-purpose programming language created by Bjarne Stroustrup. It is fast, powerful, and widely used for:

  • Games

  • Operating systems

  • Desktop applications

  • Embedded systems

  • Browsers

  • Competitive programming

  • Data Structures and Algorithms

Think of C++ as a language that allows you to give instructions to a computer.

For example:

cout << "Hello, World!";

This instruction asks the computer to display:

Hello, World!

Your first C++ program

#include <iostream>
using namespace std;

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

Let us understand it line by line.

#include <iostream>

This includes the input-output library. It provides cout for output and cin for input.

using namespace std;

This allows us to write cout instead of std::cout.

int main()

The execution of every C++ program starts from the main() function.

cout << "Hello, World!";

This displays a message on the screen.

return 0;

This tells the operating system that the program ended successfully.

Think about it

The main() function is like the main door of a house. The computer enters the program through this door.


2. How Does C++ Code Work?

A computer does not directly understand code such as:

int number = 10;

It understands only machine instructions. Therefore, C++ code must be converted into machine code.

This work is done by a compiler.

The complete process is:

C++ Source Code → Compiler → Executable File → Output

Step 1: Write the code

You write the program inside a file:

program.cpp

The .cpp extension means that it is a C++ source file.

Step 2: Compile the code

The compiler checks your program for errors and converts it into machine code.

g++ program.cpp -o program

Step 3: Run the program

On macOS or Linux:

./program

Example

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    int b = 20;

    cout << a + b;

    return 0;
}

Output:

30

The compiler first checks the program. If the code is correct, it creates an executable file. When we run that file, the computer performs the addition and displays 30.

What happens if the code is incorrect?

cout << "Hello"

This code is missing a semicolon. The compiler will report an error.

Correct code:

cout << "Hello";

A semicolon tells C++ that an instruction has ended.

Important rule

C++ is case-sensitive:

int age = 20;
int Age = 30;

age and Age are considered different variables.


3. Variables and Data Types

Imagine that you are moving into a new house. You use different boxes to store different things:

  • A small box for jewellery

  • A large box for clothes

  • A bottle for water

Similarly, a computer uses different types of memory boxes for different kinds of data. These boxes are called variables.

int age = 25;

Here:

  • int is the data type.

  • age is the name of the variable.

  • 25 is the stored value.

Common data types

Data type What it stores Example
int Whole numbers 25
float Decimal numbers 72.5f
double More precise decimals 45000.75
char One character 'A'
string Text "Amit Singh"
bool true or false true

Example program

#include <iostream>
#include <string>
using namespace std;

int main() {
    string name = "Amit";
    int age = 25;
    double salary = 55000.50;
    char grade = 'A';
    bool isTeacher = true;

    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Salary: " << salary << endl;
    cout << "Grade: " << grade << endl;
    cout << "Is Teacher: " << isTeacher << endl;

    return 0;
}

Output:

Name: Amit
Age: 25
Salary: 55000.5
Grade: A
Is Teacher: 1

C++ normally displays:

  • 1 for true

  • 0 for false

Variables can change

int score = 50;
score = 80;

cout << score;

Output:

80

The new value replaces the old value.

Constants cannot change

Use const when a value should remain fixed:

const double PI = 3.14159;

Trying to change PI later will produce an error.

Common mistake

Use single quotes for one character:

char grade = 'A';

Use double quotes for text:

string name = "Amit";

4. Input and Output Using cin and cout

So far, we have stored values directly in the program. But real applications need to communicate with their users.

C++ uses:

  • cout to display output

  • cin to accept input

Displaying output with cout

cout << "Welcome to C++";

The << operator sends the message towards the output screen.

Taking input with cin

int age;

cout << "Enter your age: ";
cin >> age;

cout << "Your age is " << age;

If the user enters 25, the output will be:

Your age is 25

The >> operator takes the entered value and stores it inside the variable.

Taking multiple inputs

int firstNumber;
int secondNumber;

cout << "Enter two numbers: ";
cin >> firstNumber >> secondNumber;

cout << "Sum = " << firstNumber + secondNumber;

Example:

Enter two numbers: 10 20
Sum = 30

Reading a complete sentence

The following code reads only one word:

string name;
cin >> name;

If the user enters Amit Singh, only Amit will be stored.

To read the complete line, use getline():

string fullName;

cout << "Enter your full name: ";
getline(cin, fullName);

cout << "Welcome, " << fullName;

Small challenge

Create a program that asks for the user’s name and favourite programming language, then displays:

Hello Amit! You like C++.

5. Operators

Operators are symbols that perform operations on data.

For example:

int total = 10 + 20;

Here, + is an operator.

Arithmetic operators

Operator Operation Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Remainder 10 % 3 1

Example:

int a = 10;
int b = 3;

cout << "Addition: " << a + b << endl;
cout << "Subtraction: " << a - b << endl;
cout << "Multiplication: " << a * b << endl;
cout << "Division: " << a / b << endl;
cout << "Remainder: " << a % b << endl;

Output:

Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Remainder: 1

Why does 10 / 3 produce 3 instead of 3.33?

Both values are integers, so C++ removes the decimal part. Use a decimal value when you need a decimal result:

cout << 10.0 / 3;

Comparison operators

Comparison operators compare two values and produce true or false.

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example:

int age = 20;

cout << (age >= 18);

Output:

1

The answer is 1 because the condition is true.

Assignment versus comparison

age = 18;

This assigns 18 to age.

age == 18;

This checks whether age is equal to 18.

Logical operators

Operator Meaning
&& Both conditions must be true
`
! Reverses the result

Example:

int age = 20;
bool hasID = true;

cout << (age >= 18 && hasID);

The result is true because the person is at least 18 and also has an ID.

Increment and decrement

int number = 5;

number++;
cout << number;

Output:

6

number++ increases the value by one, while number-- decreases it by one.


6. Conditional Statements

A program becomes useful when it can make decisions.

Consider this real-life condition:

If the traffic light is green, move. Otherwise, stop.

C++ uses conditional statements to make such decisions.

The if statement

int age = 20;

if (age >= 18) {
    cout << "You can vote.";
}

The code inside the braces runs only when the condition is true.

The if-else statement

int age;

cout << "Enter your age: ";
cin >> age;

if (age >= 18) {
    cout << "You are eligible to vote.";
} else {
    cout << "You are not eligible to vote.";
}

Only one block will execute.

The if-else if-else statement

int marks;

cout << "Enter your marks: ";
cin >> marks;

if (marks >= 90) {
    cout << "Grade A";
} else if (marks >= 75) {
    cout << "Grade B";
} else if (marks >= 50) {
    cout << "Grade C";
} else {
    cout << "Fail";
}

Conditions are checked from top to bottom. As soon as a condition becomes true, its block runs and the remaining conditions are skipped.

The switch statement

Use switch when one value can have several fixed options.

int choice;

cout << "1. Tea" << endl;
cout << "2. Coffee" << endl;
cout << "3. Juice" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
    case 1:
        cout << "You selected Tea.";
        break;

    case 2:
        cout << "You selected Coffee.";
        break;

    case 3:
        cout << "You selected Juice.";
        break;

    default:
        cout << "Invalid choice.";
}

The break statement stops execution after a matching case.

Small challenge

Write a program that accepts a number and tells whether it is:

  • Positive

  • Negative

  • Zero


7. Loops

Imagine that a teacher asks you to write “I will practise C++” 100 times.

Writing the same instruction manually would be tiring. A loop can repeat it automatically.

The for loop

Use a for loop when you know the number of repetitions.

for (int i = 1; i <= 5; i++) {
    cout << "I will practise C++." << endl;
}

The loop has three parts:

for (starting point; condition; update)

In our example:

  • int i = 1: Start from 1.

  • i <= 5: Continue until 5.

  • i++: Increase i by one.

Printing numbers from 1 to 5

for (int i = 1; i <= 5; i++) {
    cout << i << " ";
}

Output:

1 2 3 4 5

Creating a multiplication table

int number;

cout << "Enter a number: ";
cin >> number;

for (int i = 1; i <= 10; i++) {
    cout << number << " x " << i
         << " = " << number * i << endl;
}

The while loop

Use a while loop when repetition depends on a condition.

int i = 1;

while (i <= 5) {
    cout << i << " ";
    i++;
}

Always update the loop variable. Otherwise, the condition may remain true forever and create an infinite loop.

The do-while loop

A do-while loop executes its code at least once.

int password;

do {
    cout << "Enter 1234 to continue: ";
    cin >> password;
} while (password != 1234);

cout << "Access granted!";

Using break

break immediately stops the loop.

for (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;
    }

    cout << i << " ";
}

Output:

1 2 3 4

Using continue

continue skips only the current iteration.

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }

    cout << i << " ";
}

Output:

1 2 4 5

8. Functions

Imagine a coffee machine. You provide ingredients, the machine performs some work, and it gives you coffee.

A function works in a similar way:

Input → Function performs a task → Output

A function is a reusable block of code designed to perform one specific task.

Function without parameters

void greet() {
    cout << "Welcome to C++!" << endl;
}

Call it inside main():

int main() {
    greet();
    greet();

    return 0;
}

The same function can be used many times.

Function with parameters

void greet(string name) {
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet("Amit");
    greet("Rahul");

    return 0;
}

Output:

Hello, Amit!
Hello, Rahul!

name is a parameter. It allows the function to work with different values.

Function that returns a value

int add(int a, int b) {
    int sum = a + b;
    return sum;
}

Using the function:

int main() {
    int answer = add(10, 20);

    cout << "Sum = " << answer;

    return 0;
}

Output:

Sum = 30

Understanding the parts

int add(int a, int b)
  • int is the return type.

  • add is the function name.

  • a and b are parameters.

return sum;

This sends the result back to the place where the function was called.

Why are functions useful?

Functions make programs:

  • Easier to understand

  • Easier to test

  • Easier to reuse

  • Easier to fix

  • Less repetitive


9. Arrays and Strings

Arrays

Suppose you need to store the marks of five students.

Without an array:

int mark1 = 80;
int mark2 = 90;
int mark3 = 75;
int mark4 = 88;
int mark5 = 95;

With an array:

int marks[5] = {80, 90, 75, 88, 95};

An array stores multiple values of the same type under one name.

Array indexing

Array positions start from 0, not 1.

Index Value
0 80
1 90
2 75
3 88
4 95

Accessing an element:

cout << marks[0];

Output:

80

Printing an array

int marks[5] = {80, 90, 75, 88, 95};

for (int i = 0; i < 5; i++) {
    cout << marks[i] << " ";
}

Taking array input

int numbers[5];

cout << "Enter five numbers:" << endl;

for (int i = 0; i < 5; i++) {
    cin >> numbers[i];
}

Finding the total

int numbers[5] = {10, 20, 30, 40, 50};
int total = 0;

for (int i = 0; i < 5; i++) {
    total += numbers[i];
}

cout << "Total = " << total;

Output:

Total = 150

Be careful with indexes. For an array of size 5, valid indexes are 0 to 4.


Strings

A string stores text:

string name = "Amit Singh";

Include the string library:

#include <string>

Accessing characters

A string also uses zero-based indexing:

string name = "Amit";

cout << name[0] << endl;
cout << name[1] << endl;

Output:

A
m

Finding string length

string word = "Hello";

cout << word.length();

Output:

5

Joining strings

string firstName = "Amit";
string lastName = "Singh";

string fullName = firstName + " " + lastName;

cout << fullName;

Output:

Amit Singh

Reading every character

string word = "Code";

for (int i = 0; i < word.length(); i++) {
    cout << word[i] << endl;
}

Final Mini Project: Student Result Calculator

Now let us combine variables, input, loops, arrays, functions and conditions in one program.

#include <iostream>
#include <string>
using namespace std;

int calculateTotal(int marks[], int size) {
    int total = 0;

    for (int i = 0; i < size; i++) {
        total += marks[i];
    }

    return total;
}

char calculateGrade(double percentage) {
    if (percentage >= 90) {
        return 'A';
    } else if (percentage >= 75) {
        return 'B';
    } else if (percentage >= 50) {
        return 'C';
    } else {
        return 'F';
    }
}

int main() {
    string studentName;
    int marks[5];

    cout << "Enter student name: ";
    getline(cin, studentName);

    cout << "Enter marks for five subjects:" << endl;

    for (int i = 0; i < 5; i++) {
        cout << "Subject " << i + 1 << ": ";
        cin >> marks[i];
    }

    int total = calculateTotal(marks, 5);
    double percentage = total / 5.0;
    char grade = calculateGrade(percentage);

    cout << "\n----- Result -----" << endl;
    cout << "Student: " << studentName << endl;
    cout << "Total: " << total << "/500" << endl;
    cout << "Percentage: " << percentage << "%" << endl;
    cout << "Grade: " << grade << endl;

    if (grade == 'F') {
        cout << "Result: Keep practising. You can improve!";
    } else {
        cout << "Result: Congratulations! You passed.";
    }

    return 0;
}

This one program uses almost everything we learned:

  • Variables store the student’s information.

  • cin and getline() accept input.

  • cout displays the result.

  • An array stores marks.

  • A loop accepts marks for five subjects.

  • Functions calculate the total and grade.

  • Conditions decide whether the student passed.

What Should You Learn Next?

The best order for a beginner is:

Output
  ↓
Variables and Input
  ↓
Operators
  ↓
Conditions
  ↓
Loops
  ↓
Functions
  ↓
Arrays and Strings

Do not try to memorise every line. Write each program yourself, change its values, make mistakes, read the errors, and try again.

That is how programming starts becoming easy—and enjoyable.

More from this blog

Amit singh's blog

235 posts