Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

C++ Tutorial for Beginners

Published On: August 9, 2025

Are you ready to discover the fascinating world of programming? This in-depth C++ tutorial is particularly tailored for complete beginners without any coding knowledge. We begin from scratch, walking you through the basics of C++ programming using straightforward language, concise explanations, and step-by-step code examples. After following this tutorial, you’ll have a firm understanding of C plus plus and will be ready to dive deeper into more complex concepts. Explore more with our C++ Course Syllabus.

C Plus Plus Tutorial for Beginners: Your First Steps towards Coding

Imagine C++ to be a mighty instrument that assists you in making all kinds of software, ranging from games to operating systems. It may appear a bit intimidating at first, but we will dissect intricate concepts into straightforward, easy-to-follow instructions. Prepare to code your very first program and open the amazing world of coding! Let us start your C++ journey.

What is C++ and Why Should I Learn It?

Think of a language that enables you to create powerful software, from the operating system on your laptop to the games you play and the applications on your smartphone. That’s C++!

  • A Powerful and Flexible Language: C++ is fast and efficient. It provides programmers with considerable control over how the resources of the computer are utilized.
  • Foundation for Most Technologies: Most popular applications, operating systems (such as components of Windows), game engines (such as Unreal Engine), and even other programming languages have C++ as their foundation.
  • High-Demand Skill: Knowing how to write C++ code can lead to a variety of professional paths in software development, game development, system programming, and beyond.
  • Stepping Stone: Familiarity with C++ makes it easier to comprehend fundamental computer science principles that can be applied to other programming languages.

Learn at your convenient with our C++ Online Course.

Setting Up Your Development Environment for CPP

Before we get to write any C++ code, we require a location to do so! This requires two primary entities: 

  • A text editor (where you type code).
  • A compiler (which compiles your code into something the computer can process).

The most common and easy-to-use choice, particularly for Windows users, is Microsoft Visual C++ (which is included as part of Visual Studio).

Installing Visual Studio Community Edition

  • Download: Visit the official Visual Studio website and download the “Community” version. It’s free for individual developers and education.
  • Installation: Install using the installer. When asked, be sure to choose the “Desktop development with C++” workload. This has all you’ll need for C++ programming.
  • Launch: After installation, launch Visual Studio.

Your First Project in MS Visual C++ 

  • Create a New Project: In Visual Studio, select “Create a new project.”
  • Select Template: Select “Console App” (for C++). This sets up a basic project that can be run in a text window.
  • Name Your Project: Give it a useful name, such as “MyFirstProgram.”
  • Create: Click “Create.” Visual Studio will create a basic project template for you, typically with a file called Source.cpp.

Your First C++ Program: “Hello, World!”

All programmers start with “Hello, World!” This little program will print that famous greeting on your screen.

Let’s look at the code: C++

#include <iostream> // This line “includes” a library for input/output operations

int main() { // This is the main function where our program starts

    std::cout << “Hello, World!” << std::endl; // This line prints “Hello, World!” to the console

    return 0; // This tells the operating system that our program finished successfully

}

Interpreting the Code Line by Line

#include <iostream>: Visualize #include as saying to the compiler: “Hey, I’m going to make use of some utilities in a toolbox called iostream.”

  • iostream (Input/Output Stream) is a library that comes with standard C++ and offers facilities for input from the keyboard and output to the screen.

int main() { … }: This is the central piece of every C++ program. When you execute your program, the computer searches for this main function and begins to run code here.

  • int is a process that this function will “return” an integer (a whole number) once it is complete.
  • The curly braces {} are the “body” of the function – everything contained within them is part of main.

std::cout << “Hello, World!” << std::endl;: It is the instruction we use to print text onto the console. The std:: prefix indicates it’s from the “standard” namespace (more on this later).

  • The << operators (insertion operators) instruct the text “Hello, World!” to go to std::cout.
  • It’s a string literal – text between double quotes.
  • ) puts in a new line, so anything printed out subsequently will be on the next line. It also “flushes” the output buffer.

Important: Each statement in C++ needs to be terminated by a semicolon ;. This informs the compiler that the command has ended.

return 0;: This line indicates that the main function has completed successfully executing. A return value of 0 usually means no errors.

Running Your Program

Build: In Visual Studio, click on “Build” -> “Build Solution” (or press Ctrl + Shift + B). This will compile your code. If you have any typing errors (syntax errors), these will be displayed in the “Error List” window.

Run: Click on “Debug” -> “Start Without Debugging” (or press Ctrl + F5). This will run your program in a console window. You should be able to see “Hello, World!” displayed.

Congratulations! You have just written and compiled your first C++ program!

Variables: Storing Information

Imagine you want to store a number, some text, or whether something is true or false. In CPP programming, we use variables for this. A variable is like a named box in the computer’s memory where you can store a piece of information.

Declaring Variables

Before you can use a variable, you need to tell C++ two things: its type (what kind of data it will hold) and its name.

Syntax: dataType variableName;

Examples:

  • int age; // It declares age that can hold whole numbers (integers).
  • double price; // It declares price that can hold numbers with decimal points.
  • char initial; // It declares initial that can hold a single character.
  • std::string name; // It declares name that can hold a sequence of characters (text). You’ll need #include <string> for this!
  • bool isLearning; // It declares isLearning that can hold true or false.

Assigning Values to Variables

You can put a value into a variable using the = (assignment) operator.

Examples:

age = 30;

price = 19.99;

initial = ‘J’; (Notice single quotes for characters!)

name = “Alice”; (Notice double quotes for strings!)

isLearning = true;

You can also declare and assign a value in one step:

int score = 100;

std::string message = “Welcome!”;

Using Variables in Your Program

Let’s see how to use variables in a program: C++

#include <iostream>

#include <string> // Don’t forget to include <string> for std::string!

int main() {

    // Declare and initialize variables

    std::string userName = “John Doe”;

    int userAge = 25;

    double userHeight = 1.75; // meters

    // Print out the variable values

    std::cout << “Name: ” << userName << std::endl;

    std::cout << “Age: ” << userAge << ” years old” << std::endl;

    std::cout << “Height: ” << userHeight << ” meters” << std::endl;

    // Change a variable’s value

    userAge = 26;

    std::cout << “Happy Birthday! Your new age is: ” << userAge << std::endl;

    return 0;

}

Output:

Name: John Doe

Age: 25 years old

Height: 1.75 meters

Happy Birthday! Your new age is: 26

Explore all our IT training courses to upskill or reskill today.

Basic Data Types in C++

C++ has several fundamental data types to handle different kinds of information. Here are the most common ones you’ll use as a beginner:

int (Integer): It is used for whole numbers (positive, negative, or zero) without decimal points.

Examples: 5, -100, 0

double (Double-precision floating-point): It is used for numbers with decimal points. Offers good precision.

Examples: 3.14, -0.5, 100.0

float (Single-precision floating-point): Also for numbers with decimal points, but generally less precise than double. For most beginner purposes, double is preferred.

char (Character): It is used for single characters. Enclosed in single quotes.

Examples: ‘A’, ‘z’, ‘5’, ‘!’

bool (Boolean): It is used for true/false values.

Values: true or false

std::string (String): Used for sequences of characters (text). Enclosed in double quotes. Requires #include <string>.

Examples: “Hello”, “My name is Alice”

Getting Input from the User (C in C Programming)

Just like std::cout lets us display output, std::cin (pronounced “see-in”) allows your program to get input from the user (usually typed on the keyboard). This is your first step towards interactive C++ coding.

Syntax: std::cin >> variableName;

The >> operators (called extraction operators) take input from std::cin and put it into the specified variable.

Let’s write a program that asks for the user’s name and age: C++

#include <iostream>

#include <string> // For std::string

int main() {

    std::string name;

    int age;

    // Ask for name

    std::cout << “Enter your name: “;

    std::cin >> name; // Read input into the ‘name’ variable

    // Ask for age

    std::cout << “Enter your age: “;

    std::cin >> age; // Read input into the ‘age’ variable

    // Display the collected information

    std::cout << “Hello, ” << name << “!” << std::endl;

    std::cout << “You are ” << age << ” years old.” << std::endl;

    return 0;

}

Example Run:

Enter your name: Alice

Enter your age: 30

Hello, Alice!

You are 30 years old.

Important Note for std::cin:

When reading strings with std::cin >> name;, it only reads up to the first space. So if a user types “John Doe”, name will only store “John”. To read an entire line including spaces, you’d use std::getline(std::cin, name); (we’ll cover this in more detail in later tutorials).

Operators: Doing Math and Comparisons

Operators are special symbols that perform operations on values and variables.

Arithmetic Operators

These are for mathematical calculations:

  • + (Addition)
  • – (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulo – gives the remainder of a division)

Example: C++

#include <iostream>

int main() {

    int num1 = 10;

    int num2 = 3;

    std::cout << “Addition: ” << (num1 + num2) << std::endl;      // Output: 13

    std::cout << “Subtraction: ” << (num1 – num2) << std::endl;   // Output: 7

    std::cout << “Multiplication: ” << (num1 * num2) << std::endl; // Output: 30

    std::cout << “Division: ” << (num1 / num2) << std::endl;      // Output: 3 (integer division!)

    std::cout << “Modulo: ” << (num1 % num2) << std::endl;        // Output: 1

    double d1 = 10.0;

    double d2 = 3.0;

    std::cout << “Double Division: ” << (d1 / d2) << std::endl; // Output: 3.33333…

    return 0;

}

Note on Integer Division: When you divide two integers using /, C++ performs integer division, which means any decimal part is simply cut off (truncated). For precise division, at least one of the numbers should be a double or float.

Assignment Operators

These are used to assign values to variables:

  • = (Simple assignment: x = 5;)
  • += (Add and assign: x += 2; is same as x = x + 2;)
  • -= (Subtract and assign: x -= 2; is same as x = x – 2;)
  • *= (Multiply and assign: x *= 2; is same as x = x * 2;)
  • /= (Divide and assign: x /= 2; is same as x = x / 2;)
  • %= (Modulo and assign: x %= 2; is same as x = x % 2;)
Comparison Operators

These are used to compare two values. They always result in a bool (true or false) value.

  • == (Equal to: x == y)
  • != (Not equal to: x != y)
  • > (Greater than: x > y)
  • < (Less than: x < y)
  • >= (Greater than or equal to: x >= y)
  • <= (Less than or equal to: x <= y)

Example: C++

#include <iostream>

int main() {

    int a = 5;

    int b = 10;

    std::cout << “a == b: ” << (a == b) << std::endl; // 0 (false)

    std::cout << “a != b: ” << (a != b) << std::endl; // 1 (true)

    std::cout << “a < b: ” << (a < b) << std::endl;   // 1 (true)

    std::cout << “a > b: ” << (a > b) << std::endl;   // 0 (false)

    return 0;

}

Note: In C++, true is often represented as 1 and false as 0 when printed to the console.

Conditional Statements: Making Decisions (if, else if, else)

Programs often need to make decisions based on certain conditions. This is where if, else if, and else statements come in handy.

The if Statement

The if statement executes a block of code only if a specified condition is true.

Syntax:

if (condition) {

    // Code to execute if condition is true

}

Example:

#include <iostream>

int main() {

    int number = 10;

    if (number > 0) {

        std::cout << “The number is positive.” << std::endl;

    }

    return 0;

}

Output:

The number is positive.

The if-else Statement

If the condition is true, you can run one piece of code using the if-else statement; if the condition is false, you can run another block.

Syntax:

if (condition) {

    // Code to execute if condition is true

} else {

    // Code to execute if condition is false

}

Example:

#include <iostream>

int main() {

    int age = 15;

    if (age >= 18) {

        std::cout << “You are an adult.” << std::endl;

    } else {

        std::cout << “You are a minor.” << std::endl;

    }

    return 0;

}

Output:

You are a minor.

The if-else if-else Statement

You can use else if statements for more than one condition.

Syntax:

if (condition1) {

    // Code if condition1 is true

} else if (condition2) {

    // Code if condition2 is true

} else {

    // Code if none of the above conditions are true

}

Example: Simple Grade Checker

#include <iostream>

int main() {

    int score;

    std::cout << “Enter your score (0-100): “;

    std::cin >> score;

    if (score >= 90) {

        std::cout << “Excellent! Grade: A” << std::endl;

    } else if (score >= 80) {

        std::cout << “Very Good! Grade: B” << std::endl;

    } else if (score >= 70) {

        std::cout << “Good! Grade: C” << std::endl;

    } else if (score >= 60) {

        std::cout << “Pass! Grade: D” << std::endl;

    } else {

        std::cout << “Fail! Grade: F” << std::endl;

    }

    return 0;

}

Example Run:

Enter your score (0-100): 75

Good! Grade: C

Loops: Repeating Actions

Loops enable developers to execute a block of code multiple times. This is incredibly useful for repetitive tasks.

The for Loop

The for loop is ideal when you know exactly how many times you want to repeat something.

Syntax:

for (initialization; condition; update) {

    // Code to execute repeatedly

}

  • Initialization: It runs once at the beginning (e.g., int i = 0;).
  • Condition: It checked before each iteration. If the given condition is true, the loop continues; if false, it stops running.
  • Update: It runs after each iteration (e.g., i++ to increment i).

Example: Counting from 1 to 5

#include <iostream>

int main() {

    for (int i = 1; i <= 5; i++) { // i++ is shorthand for i = i + 1

        std::cout << “Count: ” << i << std::endl;

    }

    return 0;

}

Output:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

The while Loop

If a given condition is met, the while loop repeats a block of code. When you don’t know in advance how many times the loop will run, it’s helpful.

Syntax:

while (condition) {

    // Code to execute repeatedly

}

Example: User Guesses a Number

#include <iostream>

int main() {

    int secretNumber = 7;

    int guess;

    std::cout << “Guess the secret number (between 1 and 10): “;

    std::cin >> guess;

    while (guess != secretNumber) {

        std::cout << “Wrong guess! Try again: “;

        std::cin >> guess;

    }

    std::cout << “Congratulations! You guessed the secret number (” << secretNumber << “)!” << std::endl;

    return 0;

}

Example Run:

Guess the secret number (between 1 and 10): 5

Wrong guess! Try again: 9

Wrong guess! Try again: 7

Congratulations! You guessed the secret number (7)!

The do-while Loop

Similar to while, but the do-while loop always executes the code block at least once, before checking the condition.

Syntax:

do {

    // Code to execute repeatedly

} while (condition);

Example: Simplified Menu Loop

#include <iostream>

int main() {

    char choice;

    do {

        std::cout << “Enter ‘q’ to quit: “;

        std::cin >> choice;

    } while (choice != ‘q’ && choice != ‘Q’); // Keep looping until ‘q’ or ‘Q’ is entered

    std::cout << “Exited the program.” << std::endl;

    return 0;

}

Example Run:

Enter ‘q’ to quit: a

Enter ‘q’ to quit: x

Enter ‘q’ to quit: Q

Exited the program.

Functions: Organizing Your Code

With increasing programs, you start repeating chunks of code. Functions enable you to collect relevant statements into blocks that can be reused. This organizes your code:

  • More organized: Divides a big problem into small, manageable pieces.
  • Easier to read: Names give specific actions.
  • Reusable: Write once, call many times.
  • Easier to debug: Troubleshoot individual functions.

You’ve already got one on your mind: main()!

Defining a Function

Syntax:

returnType functionName(parameter1Type parameter1Name, parameter2Type parameter2Name, .) {

    // Function code block

    return value;

}

  • returnType: Data type the function will return (e.g., int, double, void if nothing). 
  • functionName: A name for your function that must be unique.
  • parameters: Variables which accept values passed as arguments into the function when invoked. They are not required.
Calling a Function

To invoke a function, you “call” it by name, supplying any required values (arguments) in parentheses.

Example:

#include <iostream>

// Function to add two numbers

int addNumbers(int a, int b) {

    int sum = a + b;

    return sum; // Return the sum

}

// Function to say hello (returns nothing, so its return type is void)

void sayHello(std::string name) {

    std::cout << “Hello, ” << name << “!” << std::endl;

}

int main() {

    // Call the addNumbers function

    int result = addNumbers(5, 3); // 5 and 3 are arguments

    std::cout << “Sum: ” << result << std::endl; // Output: Sum: 8

    // Call the sayHello function

    sayHello(“Alice”); // “Alice” is the argument

    return 0;

}

Output:

Sum: 8

Hello, Alice!

Comments: Explaining Your Code

Adding comments to your code is essential for making it comprehensible to both others and your future self. Comments are ignored by the compiler. 

  • Single-line comments: Start with //
  • Multi-line comments: Start with /* and end with */

Example:

#include <iostream>

int main() {

    // This is a single-line comment. It explains the next line.

    int age = 30; // Declare an integer variable ‘age’ and set its value to 30

    /*

     * This is a multi-line comment.

     * It can span across several lines.

     * Use it for longer explanations.

     */

    std::cout << “Your age is: ” << age << std::endl;

    return 0;

}

What’s Next? Your C++ Learning Journey!

Congratulations! You’ve taken significant steps in your learn C++ journey. You now understand the basic building blocks of C++ programming: variables, data types, input/output, operators, conditional statements, loops, and functions.

This is just the beginning! C++ is a vast and powerful language. Here are some topics you’ll want to explore next:

  • Arrays: Storing collections of similar data.
  • Pointers: Directly working with memory addresses (a core C in C programming concept).
  • Structures and Classes (Object-Oriented Programming – OOP): How to design complex software using objects. This is a fundamental aspect of modern C++.
  • File I/O: Reading from and writing to files.
  • Error Handling: How to gracefully deal with problems in your programs.
  • Standard Library Containers: Like std::vector and std::map for powerful data management.

Review your skills with our C++ interview questions and answers.

Conclusion

Remember, practice is key! The more you write CPP code, the better you’ll become. Experiment with the examples, try to modify them, and think of small programs you can build to solve simple problems.

Ready to accelerate your C++ learning and gain professional-level skills? Elevate Your Coding Journey with Our Comprehensive C++ Training Course!

Our in-depth C++ training course is designed to take you from a beginner to a confident C++ developer. You’ll gain hands-on experience with advanced concepts, best practices, and real-world projects.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.