C++


C++ Programming Language

 

This tutorial is designed for beginners who want to learn C++ from the basics, understand how programs work, practice with examples, and gradually develop the skills needed to build real applications.

 You can also use these notes as a complete C++ tutorial on your website. The lessons are arranged in a logical order, so learners can start from the first topic and progress step by step.

 

Table of contents

Beginner level

1. Introduction to C++

2. Installing a C++ compiler

3. Your first C++ program

4. Syntax, comments and output

5. Variables and data types

6. User input and output

7. Operators

8. Conditional statements

9. Loops

10. Functions

 

Intermediate level

11. Arrays and strings

12. Pointers and references

13. Structures, enumerations and type aliases

14. Object-oriented programming (OOP)

15. Constructors, destructors and encapsulation

16. Inheritance and polymorphism

17. Operator overloading

18. File handling

19. Exception handling

20. Templates

 

Advanced and practical level

21. Standard Template Library (STL)

22. Dynamic memory management

23. Modern C++ features

24. Algorithms and data structures

25. Debugging and testing

26. Common errors and best practices

27. Practical projects

28. Exercises and interview questions

 

1.Introduction to C++

What is C++?

C++ is a general-purpose programming language used to develop software applications. It supports procedural programming, object-oriented programming and generic programming.

 

A programming language allows us to give instructions to a computer. We write these instructions using a language such as C++, and a compiler translates the source code into a form the computer can execute.

For example, C++ can be used to develop:

 

  • Desktop applications
  • Games and game engines
  • Operating systems and system software
  • Embedded systems and IoT applications
  • High-performance applications
  • Database engines and development tools

 

Why learn C++?

C++ helps you understand fundamental programming concepts, including variables, decisions, loops, functions, memory and data structures.

Its main advantages include:

  • Performance: Suitable for applications that need fast execution.
  • Control: Provides control over memory and low-level system operations.
  • Flexibility: Supports multiple programming styles.
  • Transferable knowledge: Concepts such as algorithms, data structures and OOP are useful in many other languages.

 

How does a C++ program work?

1. Source code

You write instructions in a .cpp file.

2. Compiler

Checks and translates the code into machine code.

3. Executable program

The operating system runs the compiled program.

A typical workflow is: write code → compile → fix errors → run → test the output.

 

C++ versus C

C and C++ are related programming languages, but they are not identical.

Feature

C

C++

Programming style

Primarily procedural

Procedural, object-oriented and generic

Classes and objects

No built-in class system

Supported

Templates

Not supported

Supported

Memory management

Manual allocation facilities

Manual facilities plus modern resource-management techniques

Common uses

Embedded systems, operating systems

Games, systems software, high-performance applications

 

2: Setting up a C++ environment

To write and execute C++ programs, you need a code editor or IDE and a C++ compiler.

 

Option 1: Visual Studio Code

A lightweight code editor. You need to install a separate C++ compiler and configure it to build and run your programs.

Download Visual Studio Code

 

Option 2: Code::Blocks

An IDE often used by beginners. Choose an installer that includes a compiler, such as a MinGW-enabled package where available.

Download Code::Blocks

 

Option 3: Online compiler

You can practise immediately in your browser without installing software.

 

Open online C++ compiler

For a beginner, an online compiler is the quickest way to start learning.

 

3.Your first C++ program

Let us create the simplest C++ program.

#include <iostream>

using namespace std;

 

int main() {

cout << "Hello, World!";

return 0;

}

Output:

Hello, World!

 

Understand each line

Code

Meaning

#include <iostream>

Includes standard input/output facilities.

using namespace std;

Lets us use standard-library names such as cout without writing std:: each time.

int main()

Defines the main function, where program execution begins.

{ }

Marks the beginning and end of a block.

cout

Sends output to the standard output stream.

return 0;

Indicates successful completion of main.

 

You can also write std::cout instead of cout, which is often preferable in larger programs.

 

Display multiple lines

#include <iostream>

using namespace std;

 

int main() {

cout << "My name is Alex." << endl;

cout << "I am learning C++." << endl;

cout << "This is my first program.";

return 0;

}

Output:

My name is Alex.

I am learning C++.

This is my first program.

endl ends the current line and flushes the output stream. You can also use \n to start a new line.

cout << "Hello\nWorld";

Output:

Hello

World

 

Important syntax rules

  • C++ is case-sensitive: main, Main and MAIN are different.
  • Most statements end with a semicolon (;).
  • Opening and closing braces must match.
  • Text literals are enclosed in double quotation marks.
  • A C++ source file commonly uses the .cpp extension.

 

4: Comments and program readability

Comments explain code to human readers. The compiler ignores comments.

Single-line comment

// This program displays a greeting

cout << "Welcome!";

Multi-line comment

/*

This program demonstrates

how to write multiple lines

inside a comment.

*/

cout << "Welcome!";

Use comments to explain why something is done when the reason is not obvious. Clear variable and function names are also important.

 

5: Variables and data types

What is a variable?

A variable is a named storage location used to hold a value that a program can access and, when appropriate, change.

 

Imagine a box labelled age that stores the number 20. The label is the variable name, and the stored value is 20.

int age = 20;

Here:

  • int is the data type.
  • age is the variable name.
  • 20 is the initial value.
  • = assigns the initial value.

 

Common C++ data types

Data type

Purpose

Example

int

Whole numbers

int age = 20;

float

Floating-point numbers

float height = 1.75f;

double

Floating-point numbers with greater typical precision

double price = 99.99;

char

A single character

char grade = 'A';

bool

True or false

bool isStudent = true;

string

Text

string name = "Alex";

 

To use string, include the appropriate header:

#include <iostream>

#include <string>

using namespace std;

 

int main() {

string name = "Alex";

int age = 20;

double marks = 85.5;

bool passed = true;

 

cout << name << "\n";

cout << age << "\n";

cout << marks << "\n";

cout << passed << "\n";

 

return 0;

}

By default, printing a bool displays 1 for true and 0 for false. You can use boolalpha to display true and false.

 

Declaring and updating variables

int score = 50;  // Declaration and initialization

score = 75;      // Update the value

 

cout << score;

Output:

75

A declaration introduces a variable. Initialization gives it its first value. Assignment changes its value later.

 

Constants

A constant is a value that cannot be reassigned after initialization.

const double PI = 3.14159;

Use const when a value should remain unchanged.

 

Rules for naming variables

Valid examples:

int age;

int studentAge;

int total_marks;

int number1;

Invalid examples:

// int 1number;       // Cannot start with a digit

// int student age;   // Spaces are not allowed

// int class;         // Reserved keyword

Choose meaningful names such as totalPrice, studentName and numberOfItems.

 

6: User input and output

Programs become interactive when they accept input from users.

 

Using cin

The cin stream reads input from the user.

#include <iostream>

using namespace std;

 

int main() {

int age;

 

cout << "Enter your age: ";

cin >> age;

 

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

 

return 0;

}

Example interaction:

Enter your age: 22

Your age is 22

The >> operator extracts a value from the input stream and stores it in age.

Read more than one value

int a, b;

 

cout << "Enter two numbers: ";

cin >> a >> b;

 

cout << "Sum = " << a + b;

Example input: 10 20

Output:

Sum = 30

 

Reading a full line of text

cin >> name stops at whitespace. To read a full line, use getline().

#include <iostream>

#include <string>

using namespace std;

 

int main() {

string fullName;

 

cout << "Enter your full name: ";

getline(cin, fullName);

 

cout << "Welcome, " << fullName;

 

return 0;

}

If you use getline() immediately after reading another value with cin >>, a leftover newline may cause it to read an empty line. In that situation, use cin.ignore() appropriately before getline().

 

7: Operators in C++

Operators perform calculations, comparisons and logical operations.

Arithmetic operators

Operator

Meaning

Example

+

Addition

10 + 5 → 15

-

Subtraction

10 - 5 → 5

*

Multiplication

10 * 5 → 50

/

Division

10 / 5 → 2

%

Remainder

10 % 3 → 1

 

Important: when both operands are integers, division discards the fractional part.

cout << 7 / 2;     // 3

cout << 7.0 / 2;   // 3.5

 

Assignment operators

int x = 10;

x += 5;  // x = x + 5

x -= 2;  // x = x - 2

x *= 3;  // x = x * 3

x /= 2;  // x = x / 2

After these statements, x is 19.

 

Comparison operators

Comparison expressions produce a Boolean result.

Operator

Meaning

==

Equal to

!=

Not equal to

> 

Greater than

< 

Less than

>=

Greater than or equal to

<=

Less than or equal to

For example:

int a = 10;

int b = 20;

 

cout << (a < b);   // 1 (true)

cout << (a == b);  // 0 (false)

Do not confuse = (assignment) with == (comparison).

 

Logical operators

  • && — AND: both conditions must be true.
  • || — OR: at least one condition must be true.
  • ! — NOT: reverses a Boolean value.

int age = 25;

bool hasID = true;

 

if (age >= 18 && hasID) {

cout << "Access allowed";

}

 

Increment and decrement

int x = 5;

 

x++;  // x becomes 6

x--;  // x becomes 5

++x increments before its value is used in an expression; x++ uses the old value first. When used as standalone statements, both increment x by one.

 

8: Conditional statements

Conditional statements allow a program to make decisions.

The if statement

int age = 20;

 

if (age >= 18) {

cout << "You are an adult.";

}

The code inside the block executes only when the condition is true.

 

The if-else statement

int number = 7;

 

if (number % 2 == 0) {

cout << "Even number";

} else {

cout << "Odd number";

}


Output:

Odd number

 

The else if statement

Use else if when you need to check multiple conditions.

int marks = 78;

 

if (marks >= 75) {

cout << "Distinction";

} else if (marks >= 50) {

cout << "Pass";

} else {

cout << "Fail";

}

Output:

Distinction

Conditions are evaluated in order. Once a condition matches, the remaining branches are skipped.

 

Nested if statements

An if statement can appear inside another if statement.

int age = 22;

bool hasTicket = true;

 

if (age >= 18) {

if (hasTicket) {

cout << "You may enter.";

}

}

Nested conditions can be useful, but for simple cases you can often combine them using &&.

 

The switch statement

A switch is useful when a variable is compared against several discrete values.

int day = 2;

 

switch (day) {

case 1:

cout << "Monday";

break;

case 2:

cout << "Tuesday";

break;

case 3:

cout << "Wednesday";

break;

default:

cout << "Invalid day";

}

Output:

Tuesday

break prevents execution from continuing into the next case. The default case handles values that do not match the listed cases.

 

The ternary operator

The conditional or ternary operator is a compact alternative for choosing between two values.

int age = 20;

 

string result = (age >= 18) ? "Adult" : "Minor";

 

cout << result;

Use if-else for complex decision-making so the code remains easy to read.

9: Loops

A loop repeats a block of code while a condition is satisfied or for a specified number of iterations.

C++ provides three main loop structures: for, while and do-while.

 

The for loop

Use a for loop when the number of repetitions is known or controlled by a counter.

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

cout << i << "\n";

}

Output:

1

2

3

4

5

Understand the three parts:

  • int i = 1 initializes the counter.
  • i <= 5 is the condition.
  • i++ updates the counter after each iteration.

 

The while loop

A while loop checks its condition before executing its body.

int i = 1;

 

while (i <= 5) {

cout << i << "\n";

i++;

}

The loop continues until the condition becomes false.

 

The do-while loop

A do-while loop executes its body at least once because the condition is checked afterward.

int i = 1;

 

do {

cout << i << "\n";

i++;

} while (i <= 5);

Notice the semicolon after while (i <= 5);.

 

break and continue

break exits a loop. continue skips the rest of the current iteration and proceeds to the next one.

for (int i = 1; i <= 10; i++) {

if (i == 5) {

continue;

}

 

cout << i << " ";

}

Output:

1 2 3 4 6 7 8 9 10

 

Nested loops

A nested loop is a loop inside another loop.

for (int row = 1; row <= 3; row++) {

for (int col = 1; col <= 3; col++) {

cout << "* ";

}

cout << "\n";

}

Output:

* * *

* * *

* * *

The outer loop controls the rows, while the inner loop controls the columns.

 

Practical example: multiplication table

#include <iostream>

using namespace std;

 

int main() {

int number;

 

cout << "Enter a number: ";

cin >> number;

 

for (int i = 1; i <= 10; i++) {

cout << number << " x " << i

<< " = " << number * i << "\n";

}

 

return 0;

}

This program combines input, variables, arithmetic and loops.

 

10: Functions

What is a function?

A function is a named block of code that performs a particular task. Functions help you organize code, reuse logic and test individual parts of a program.

For example, instead of writing the same calculation several times, you can write one function and call it whenever needed.

 

Defining and calling a function

#include <iostream>

using namespace std;

 

void greet() {

cout << "Welcome to C++!";

}

 

int main() {

greet();

return 0;

}

Here, greet() is the function name, void means it does not return a value, and main() calls it.

 

Parameters and arguments

Parameters allow functions to receive data.

void greet(string name) {

cout << "Hello, " << name;

}

 

int main() {

greet("Alex");

return 0;

}

name is the parameter. "Alex" is the argument passed to the function.

 

Return values

A function can calculate and return a value.

int add(int a, int b) {

return a + b;

}

 

int main() {

int result = add(10, 20);

cout << result;

return 0;

}

Output:

30

The return type int indicates that the function returns an integer.

 

Function prototypes

A prototype declares a function before its definition, allowing it to be called earlier in the source file.

#include <iostream>

using namespace std;

 

int multiply(int a, int b);

 

int main() {

cout << multiply(4, 5);

return 0;

}

 

int multiply(int a, int b) {

return a * b;

}

 

Function overloading

C++ allows several functions to share a name when their parameter lists differ.

int add(int a, int b) {

return a + b;

}

 

double add(double a, double b) {

return a + b;

}

The compiler selects the appropriate overload based on the arguments. Changing only the return type is not sufficient to overload a function.

 

Pass by value and pass by reference

Pass by value gives a function its own copy of a value.

void change(int x) {

x = 100;

}

Changing x does not change the original variable.

Pass by reference lets a function work with the original variable.

void change(int& x) {

x = 100;

}

 

int main() {

int number = 10;

change(number);

cout << number; // 100

}

The & in the parameter declaration indicates a reference. Reference parameters are useful when a function needs to modify an argument without copying it.

 

Recursion

Recursion occurs when a function calls itself. Every recursive solution needs a base case to stop the calls.

int factorial(int n) {

if (n <= 1) {

return 1;

}

 

return n * factorial(n - 1);

}

For example, factorial(5) returns .

This example assumes a non-negative input and uses a simplified base case. Production code should validate the input and account for integer overflow.

 

11: Arrays and strings

What is an array?

An array stores multiple elements of the same type in a sequence.

int marks[5] = {75, 80, 65, 90, 85};

 

cout << marks[0];

Output:

75

C++ arrays use zero-based indexing. The first element is at index 0; the fifth element in this array is at index 4.

Accessing an index outside the array's valid range causes undefined behavior for a built-in array.

 

Loop through an array

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

 

for (int i = 0; i < 5; i++) {

cout << numbers[i] << " ";

}

Output:

10 20 30 40 50

 

Find the sum and average

#include <iostream>

using namespace std;

 

int main() {

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

int sum = 0;

 

for (int i = 0; i < 5; i++) {

sum += numbers[i];

}

 

double average = sum / 5.0;

 

cout << "Sum: " << sum << "\n";

cout << "Average: " << average;

 

return 0;

}

Output:

Sum: 150

Average: 30

Using 5.0 ensures the division uses floating-point arithmetic.

 

Multidimensional arrays

A two-dimensional array can represent rows and columns.

int matrix[2][3] = {

{1, 2, 3},

{4, 5, 6}

};

 

cout << matrix[1][2];

Output:

6

The first index selects the row, and the second selects the column.

 

C++ strings

Use std::string to work with text.

#include <iostream>

#include <string>

using namespace std;

 

int main() {

string firstName = "Alex";

string lastName = "Perera";

 

string fullName = firstName + " " + lastName;

 

cout << fullName << "\n";

cout << fullName.length();

 

return 0;

}

Output:

Alex Perera

12

Useful string operations include:

string text = "Programming";

 

cout << text.length();       // Number of characters

cout << text[0];             // First character

cout << text.substr(0, 4);   // "Prog"

cout << text.find("gram");  // Starting position, if found

If a substring is not found, find() returns string::npos.

 

vector: a flexible alternative to arrays

A vector is a dynamic-size sequence from the C++ Standard Library.

#include <iostream>

#include <vector>

using namespace std;

 

int main() {

vector<int> numbers

Files, images, and data analysis are unavailable until usage resets at 1:11 PM. Continue chatting with text only, or upgrade for more access.

 

Learn C++ Programming at UNITEC

Turn Your Programming Ideas into Real Applications with C++

At UNITEC – Uni of Technology, Vavuniya, students can develop their programming knowledge and practical software development skills through structured learning and hands-on practice.

 

Our C++ programming lessons cover essential concepts, from basic programming fundamentals to advanced techniques, helping students build a strong foundation in software development.

 

What You Will Learn

  • C++ Fundamentals, Syntax and Data Types
  • Variables, Operators and Control Statements
  • Loops, Functions and Arrays
  • Strings, Pointers and Memory Management
  • Object-Oriented Programming (OOP)
  • Classes, Objects, Inheritance and Polymorphism
  • File Handling and Exception Handling
  • Templates and the Standard Template Library (STL)
  • Data Structures, Algorithms and Problem-Solving
  • Debugging, Testing and Practical Project Development

 

Learn by Practising

At UNITEC, learners can apply programming concepts through practical exercises and project-based learning, developing their ability to write, understand and improve C++ programs.

 

Whether you are beginning your programming journey or strengthening your existing knowledge, these tutorials can help you progress step by step.

Start learning C++ today and take your first step towards a future in software development!

UNITEC – Learn. Build. Grow.

 

Top of Form

 

Contact UNITEC Campus

Address:
10th Lane, Vairavapuliyankulam, Vavuniya, Sri Lanka

 

Phone:

077 137 7675

 

Website:
unitec.edu.lk

Bottom of Form