C++ Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 191

C++ Programming

C++ history
History of C++ language is interesting to know. Here we
are going to discuss brief history of C++ language.

C++ programming language was developed in 1980 by


Bjarne Stroustrup at bell laboratories of AT&T (American
Telephone & Telegraph), located in U.S.A.

Bjarne Stroustrup is known as the founder of C++


language.

It was develop for adding a feature of OOP (Object


Oriented Programming) in C without significantly changing
the C component.

C++ programming is "relative" (called a superset) of C, it means any valid C program is also
a valid C++ program.

Let's see the programming languages that were developed before C++ language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie


K&RC 1978 Kernighan & Dennis Ritchie

C++ 1980 Bjarne Stroustrup

C++ Features
C++ is object oriented programming language. It provides a lot of features that are given
below.

Simple

Machine Independent or Portable

Mid-level programming language


Structured programming language

Rich Library

Memory Management

Fast Speed

Pointers

Recursion

Extensible

Object Oriented

Compiler based

1) Simple

C++ is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with little bit or
no change. But it is not platform-independent.

3) Mid-level programming language

C++ is also used to do low level programming. It is used to develop system applications such
as kernel, driver etc. It also supports the feature of high level language. That is why it is
known as mid-level language.

4) Structured programming language

C++ is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify.

5) Rich Library

C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C++ language, we can free the
allocated memory at any time by calling the free() function.
7) Speed

The compilation and execution time of C++ language is fast.

8) Pointer

C++ provides the feature of pointers. We can directly interact with the memory by using
the pointers. We can use pointers for memory, structures, functions, array etc.

9) Recursion

In C++, we can call the function within the function. It provides code reusability for every
function.

10) Extensible

C++ language is extensible because it can easily adopt new features.

11) Object Oriented

C++ is object oriented programming language. OOPs makes development and maintenance
easier where as in Procedure-oriented programming language it is not easy to manage if
code grows as project size grows.

12) Compiler based

C++ is a compiler based programming language, it means without compilation no C++ program
can be executed. First we need to compile our program using compiler and then we can
execute our program.

C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed
and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

type variable_list;

The example of declaring variable is given below:

int x=10;

float y;

char z;
Here, x, y, z are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

int x=5,b=10; //declaring 2 variable of integer type

float f=30.8;

char c='A';

Rules for defining variables

A variable can have alphabets, digits and underscore.

A variable name can start with alphabet and underscore only. It can't start with digit.

No white space is allowed within variable name.

A variable name must not be any reserved word or keyword e.g. char, float etc.

C++ Data Types


A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure

Basic Data Types

The basic data types are integer-based and floating-point based. C++ language supports
both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating
system.

Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range

char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

int 2 byte -32,768 to 32,767

unsigned int 2 byte 0 to 32,767


float 4 byte

double 8 byte

C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A
list of 32 Keywords in C++ Language which are also available in C language are given below.

auto break case char const continue default do

double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given below.

asm dynamic_cast namespace reinterpret_cast bool

explicit new static_cast false catch

operator template friend private class

this inline public throw const_cast

delete mutable protected true try


typeid typename using virtual wchar_t

C++ Operators

Operators are symbols that perform operations on variables and values. For example, + is
an operator used for addition, while - is an operator used for subtraction.

Operators in C++ can be classified into 6 types:

Arithmetic Operators

Assignment Operators

Relational Operators

Logical Operators

Bitwise Operators

Other Operators

1. C++ Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,

a + b;

Here, the + operator is used to add two variables a and b. Similarly there are various other
arithmetic operators in C++.

Operator Operation

+ Addition
- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

Increment and Decrement Operators

C++ also provides increment and decrement operators: ++ and -- respectively.

++ increases the value of the operand by 1

-- decreases it by 1

2. C++ Assignment Operators

In C++, assignment operators are used to assign values to variables. For example,

// assign 5 to a

a = 5;

Here, we have assigned a value of 5 to the variable a.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;
*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

3. C++ Relational Operators

A relational operator is used to check the relationship between two operands. For example,

// checks if a is greater than b

a > b;

Here, > is a relational operator. It checks if a is greater than b or not.

If the relation is true, it returns 1 whereas if the relation is false, it returns 0.

Operator Meaning Example

== Is Equal To 3 == 5 gives us false

!= Not Equal To 3 != 5 gives us true

> Greater Than 3 > 5 gives us false

< Less Than 3 < 5 gives us true

>= Greater Than or Equal To 3 >= 5 give us false

<= Less Than or Equal To 3 <= 5 gives us true


4. C++ Logical Operators

Logical operators are used to check whether an expression is true or false. If the
expression is true, it returns 1 whereas if the expression is false, it returns 0.

Operator Example Meaning

expression1 && Logical AND.


&&
expression2 True only if all the operands are true.

Logical OR.
|| expression1 || expression2 True if at least one of the operands is
true.

Logical NOT.
! !expression
True only if the operand is false.

5. C++ Bitwise Operators

In C++, bitwise operators are used to perform operations on individual bits. They can only
be used alongside char and int data types.

Operator Description

& Binary AND

| Binary OR

^ Binary XOR
~ Binary One's Complement

<< Binary Shift Left

>> Binary Shift Right

6. Other C++ Operators

Here's a list of some other common operators available in C++. We will learn about them in
later tutorials.

Operator Description Example

sizeof returns the size of data type sizeof(int); // 4

string result = (5 > 0) ? "even" :


?: returns value based on the condition
"odd"; // "even"

represents memory address of the


& # // address of num
operand

accesses members of struct variables


. s1.marks = 92;
or class objects

used with pointers to access the class


-> ptr->marks = 92;
or struct variables

<< prints the output value cout << 5;


>> gets the input value cin >> num;

C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions,
arrays, or other user-defined data types created by the programmer. They are the basic
requirement of any language. Every language has its own rules for naming the identifiers.

In short, we can say that the C++ identifiers represent the essential elements in a program
which are given below:

Constants

Variables

Functions

Labels

Defined data types

Some naming rules are common in both C and C++. They are as follows:

Only alphabetic characters, digits, and underscores are allowed.

The identifier name cannot start with a digit, i.e., the first letter should be alphabetical.
After the first letter, we can use letters, digits, or underscores.

In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.

A declared keyword cannot be used as a variable name.

C++ Program

Before starting the abcd of C++ language, you need to learn how to write, compile and run
the first C++ program.

To write the first C++ program, open the C++ console and write the following code:
#include <iostream.h>

#include<conio.h>

void main()

clrscr();

cout << "Welcome to C++ Programming.";

getch();

#include<iostream.h> includes the standard input output library functions. It


provides cin and cout methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch() function
is defined in conio.h file.

void main() The main() function is the entry point of every program in C++ language. The
void keyword specifies that it returns no value.

cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.

getch() The getch() function asks for a single character. Until you press any key, it blocks
the screen.
How to compile and run the C++ program

There are 2 ways to compile and run the C++ program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c++ program.

Then click on the run menu then run sub menu to run the c++ program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.


You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

Program to print Hello World!

#include <iostream>

using namespace std;

int main()

cout << "Hello, World!";

return 0;

Output

Hello, World!

Program to Add Two Number or Integers

#include <iostream>

using namespace std;

int main()

int firstNumber, secondNumber, sumOfTwoNumbers;


cout << "Enter two integers: ";

cin >> firstNumber >> secondNumber;

// sum of two numbers in stored in variable sumOfTwoNumbers

sumOfTwoNumbers = firstNumber + secondNumber;

// Prints sum

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

return 0;

Output

Enter two integers: 4

4+5=9

Program to Find Size of a Variable

#include <iostream>

using namespace std;

int main()

cout << "Size of char: " << sizeof(char) << " byte" << endl;

cout << "Size of int: " << sizeof(int) << " bytes" << endl;

cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;

return 0;

Output

Size of char: 1 byte

Size of int: 4 bytes

Size of float: 4 bytes

Size of double: 8 bytes

Program to Compute quotient and remainder

#include <iostream>

using namespace std;

int main()

int divisor, dividend, quotient, remainder;

cout << "Enter dividend: "; cin >> dividend;

cout << "Enter divisor: "; cin >> divisor;

quotient = dividend / divisor;

remainder = dividend % divisor;

cout << "Quotient = " << quotient << endl;

cout << "Remainder = " << remainder;

return 0;

Output

Enter dividend: 13

Enter divisor: 4
Quotient = 3

Remainder = 1

Program to Swap Numbers (Using Temporary Variable)

#include <iostream>

using namespace std;

int main()

int a = 5, b = 10, temp;

cout << "Before swapping." << endl;

cout << "a = " << a << ", b = " << b << endl;

temp = a;

a = b;

b = temp;

cout << "\nAfter swapping." << endl;

cout << "a = " << a << ", b = " << b << endl;

return 0;

Output

Before swapping.

a = 5, b = 10

After swapping.

a = 10, b = 5

Program to Print ASCII Value


#include <iostream>

using namespace std;

int main()

char c;

cout << "Enter a character: "; cin >> c;

cout << "ASCII Value of " << c << " is " << int(c);

return 0;

Output

Enter a character: p

ASCII Value of p is 112

Control Statement
Sometimes we need to execute a block of statements only when a particular condition is
met or not met. This is called decision making, as we are executing a certain code after
making a decision in the program logic. For decision making in C++, we have four types of
control statements (or control structures), which are as follows:

a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

If statement in C++
If statement consists a condition, followed by statement or a set of statements as shown
below:

if(condition){

Statement(s);

The statements inside if parenthesis (usually referred as if body) gets executed only when
the given condition is true. If the condition is false then the statements inside if body are
completely ignored.

Example 1: C++ if Statement

// Program to print positive number entered by the user

// If the user enters a negative number, it is skipped

#include <iostream>

using namespace std;

int main() {

int number;

cout << "Enter an integer: ";

cin >> number;

// checks if the number is positive

if (number > 0) {

cout << "You entered a positive integer: " << number << endl;

cout << "This statement is always executed.";

return 0;
}

Output

Enter an integer: 5

You entered a positive number: 5

This statement is always executed.

If else statement in C++

Sometimes you have a condition and you want to execute a block of code if condition is
true and execute another piece of code if the same condition is false. This can be achieved
in C++ using if-else statement.

This is how an if-else statement looks:

if(condition) {

Statement(s);

else {

Statement(s);

The statements inside “if” would execute if the condition is true, and the statements
inside “else” would execute if the condition is false.

Example 2: C++ if...else Statement

// Program to check whether an integer is positive


or negative

// This program considers 0 as a positive number

#include <iostream>

using namespace std;

int main() {

int number;
cout << "Enter an integer: ";

cin >> number;

if (number >= 0) {

cout << "You entered a positive integer: " << number << endl;

else {

cout << "You entered a negative integer: " << number << endl;

cout << "This line is always printed.";

return 0;

Output

Enter an integer: 4

You entered a positive integer: 4.

This line is always printed.

Example of if-else statement

#include <iostream>

using namespace std;

int main(){

int num=66;

if( num < 50 ){

//This would run if above condition is true

cout<<"num is less than 50";

}
else {

//This would run if above condition is false

cout<<"num is greater than or equal 50";

return 0;

C++ If-else Example: with input from user

#include <iostream>

using namespace std;

int main () {

int num;

cout<<"Enter a Number: ";

cin>>num;

if (num % 2 == 0)

cout<<"It is even number"<<endl;

else

cout<<"It is odd number"<<endl;

return 0;

Output:

Enter a number:11
It is odd number

C++ IF-else-if ladder Statement


The C++ if-else-if ladder statement executes one condition from multiple statements.

if(condition1){

//code to be executed if condition1 is true

}else if(condition2){

//code to be executed if condition2 is true

else if(condition3){

//code to be executed if condition3 is true

...

else

{
//code to be executed if all the conditions are false

C++ If else-if Example

#include <iostream>

using namespace std;

int main () {

int num;

cout<<"Enter a number to check grade:";

cin>>num;

if (num <0 || num >100)

cout<<"wrong number";

else if(num >= 0 && num < 50){

cout<<"Fail";

else if (num >= 50 && num < 60)

cout<<"D Grade";

else if (num >= 60 && num < 70)

cout<<"C Grade";

}
else if (num >= 70 && num < 80)

cout<<"B Grade";

else if (num >= 80 && num < 90)

cout<<"A Grade";

else if (num >= 90 && num <= 100)

cout<<"A+ Grade";

Output:

Enter a number to check grade:66

C Grade

Program to Find Largest Number Using if Statement

#include <iostream>

using namespace std;

int main()

float n1, n2, n3;

cout << "Enter three numbers: ";

cin >> n1 >> n2 >> n3;


if(n1 >= n2 && n1 >= n3)

cout << "Largest number: " << n1;

if(n2 >= n1 && n2 >= n3)

cout << "Largest number: " << n2;

if(n3 >= n1 && n3 >= n2) {

cout << "Largest number: " << n3;

return 0;

Output

Enter three numbers: 2.3

8.3

-4.2

Largest number: 8.3

Program to Check Vowel or a Consonant Manually

#include <iostream>

using namespace std;

int main()

char c;

int isLowercaseVowel, isUppercaseVowel;


cout << "Enter an alphabet: ";

cin >> c;

// evaluates to 1 (true) if c is a lowercase vowel

isLowercaseVowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');

// evaluates to 1 (true) if c is an uppercase vowel

isUppercaseVowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');

// evaluates to 1 (true) if either isLowercaseVowel or isUppercaseVowel is true

if (isLowercaseVowel || isUppercaseVowel)

cout << c << " is a vowel.";

else

cout << c << " is a consonant.";

return 0;

Output

Enter an alphabet: u

u is a vowel.

C++ switch
The C++ switch statement executes one
statement from multiple conditions. It is like if-
else-if ladder statement in C++.

switch(expression){

case value1:

//code to be executed;

break;

case value2:
//code to be executed;

break;

......

default:

//code to be executed if all cases are not matched;

break;

C++ Switch Example

#include <iostream>

using namespace std;

int main () {

int num;

cout<<"Enter a number to check grade:";

cin>>num;

switch (num)

case 10: cout<<"It is 10"; break;

case 20: cout<<"It is 20"; break;

case 30: cout<<"It is 30"; break;

default: cout<<"Not 10, 20 or 30"; break;

Output:
Enter a number:

10

It is 10

Example: Create a Calculator using the switch Statement

// Program to build a simple calculator using switch Statement

#include <iostream>

using namespace std;

int main() {

char oper;

float num1, num2;

cout << "Enter an operator (+, -, *, /): ";

cin >> oper;

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

cin >> num1 >> num2;

switch (oper) {

case '+':

cout << num1 << " + " << num2 << " = " << num1 + num2;

break;

case '-':

cout << num1 << " - " << num2 << " = " << num1 - num2;

break;

case '*':

cout << num1 << " * " << num2 << " = " << num1 * num2;

break;

case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;

break;

default:

// operator is doesn't match any case constant (+, -, *, /)

cout << "Error! The operator is not correct";

break;

return 0;

Output 1

Enter an operator (+, -, *, /): +

Enter two numbers:

2.3

4.5

2.3 + 4.5 = 6.8

Example

#include <iostream>

using namespace std;

int main () {

// local variable declaration:

char grade = 'D';

switch(grade) {

case 'A' :
cout << "Excellent!" << endl;

break;

case 'B' :

case 'C' :

cout << "Well done" << endl;

break;

case 'D' :

cout << "You passed" << endl;

break;

case 'F' :

cout << "Better try again" << endl;

break;

default :

cout << "Invalid grade" << endl;

cout << "Your grade is " << grade << endl;

return 0;

This would produce the following result −

You passed

Your grade is D
C++ For Loop
The C++ for loop is used to iterate a part of the
program several times. If the number of
iteration is fixed, it is recommended to use for
loop than while or do-while loops.

The C++ for loop is same as C/C#. We can


initialize variable, check condition and
increment/decrement value.

for(initialization; condition; incr/decr)

//code to be executed

Flowchart:

C++ For Loop Example

#include <iostream>

using namespace std;

int main() {

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

cout<<i <<"\n";

Output:

4
5

10

Example 3: Find the sum of first n Natural Numbers

// C++ program to find the sum of first n natural numbers

// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>

using namespace std;

int main() {

int num, sum;

sum = 0;

cout << "Enter a positive integer: ";

cin >> num;

for (int count = 1; count <= num; ++count) {

sum += count;

cout << "Sum = " << sum << endl;

return 0;

Output

Enter a positive integer: 10

Sum = 55
Example: Find Factorial of a given number

#include <iostream>

using namespace std;

int main()

int n;

unsigned long long factorial = 1;

cout << "Enter a positive integer: ";

cin >> n;

if (n < 0)

cout << "Error! Factorial of a negative number doesn't exist.";

else {

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

factorial *= i;

cout << "Factorial of " << n << " = " << factorial;

return 0;

Output

Enter a positive integer: 12

Factorial of 12 = 479001600
Example 1: Fibonacci Series up to n number of terms

#include <iostream>

using namespace std;

int main() {

int n, t1 = 0, t2 = 1, nextTerm = 0;

cout << "Enter the number of terms: ";

cin >> n;

cout << "Fibonacci Series: ";

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

// Prints the first two terms.

if(i == 1) {

cout << t1 << ", ";

continue;

if(i == 2) {

cout << t2 << ", ";

continue;

nextTerm = t1 + t2;

t1 = t2;

t2 = nextTerm;

cout << nextTerm << ", ";

return 0;

}
Output

Enter the number of terms: 10

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Example 1: Program to print half pyramid using *

**

***

****

*****

Source Code

#include <iostream>

using namespace std;

int main()

int rows;

cout << "Enter number of rows: ";

cin >> rows;

for(int i = 1; i <= rows; ++i)

for(int j = 1; j <= i; ++j)

cout << "* ";

cout << "\n";

}
return 0;

Example 2: Program to print half pyramid a using numbers

12

123

1234

12345

Source Code

#include <iostream>

using namespace std;

int main()

int rows;

cout << "Enter number of rows: ";

cin >> rows;

for(int i = 1; i <= rows; ++i)

for(int j = 1; j <= i; ++j)

cout << j << " ";

cout << "\n";

return 0;
}

Example 4: Inverted half pyramid using *

*****

****

***

**

Source Code

#include <iostream>

using namespace std;

int main()

int rows;

cout << "Enter number of rows: ";

cin >> rows;

for(int i = rows; i >= 1; --i)

for(int j = 1; j <= i; ++j)

cout << "* ";

cout << endl;

return 0;

}
Example 5: Inverted half pyramid using numbers

12345

1234

123

12

Source Code

#include <iostream>

using namespace std;

int main()

int rows;

cout << "Enter number of rows: ";

cin >> rows;

for(int i = rows; i >= 1; --i)

for(int j = 1; j <= i; ++j)

cout << j << " ";

cout << endl;

return 0;

}
Example : Print Floyd's Triangle.

23

456

7 8 9 10

Source Code

#include <iostream>

using namespace std;

int main()

int rows, number = 1;

cout << "Enter number of rows: ";

cin >> rows;

for(int i = 1; i <= rows; i++)

for(int j = 1; j <= i; ++j)

cout << number << " ";

++number;

cout << endl;

return 0;

}
Example: C++ program to print full star pyramid pattern

***

*****

*******

*********

#include <iostream>

using namespace std;

int main()

int rows, i, j, space;

cout << "Enter number of rows: ";

cin >> rows;

for(i = 1; i <= rows; i++)

//for loop for displaying space

for(space = i; space < rows; space++)

cout << " ";

//for loop to display star equal to row number

for(j = 1; j <= (2 * i - 1); j++)

cout << "*";


}

cout << "\n";

return 0;

C++ while Loop


The syntax of the while loop is:

while (condition) {

// body of the loop

Here,

A while loop evaluates the condition

If the condition evaluates to true, the code


inside the while loop is executed.

The condition is evaluated again.

This process continues until


the condition is false.

When the condition evaluates to false, the


loop terminates.

Example 1: Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {
int i = 1;

// while loop from 1 to 5

while (i <= 5) {

cout << i << " ";

++i;

return 0;

Output

12345

Example 2: Sum of Positive Numbers Only

// program to find the sum of positive numbers

// if the user enters a negative number, the loop ends

// the negative number entered is not added to the sum

#include <iostream>

using namespace std;

int main() {

int number;

int sum = 0;

// take input from the user

cout << "Enter a number: ";

cin >> number;

while (number >= 0) {

// add all positive numbers

sum += number;
// take input again if the number is positive

cout << "Enter a number: ";

cin >> number;

// display the sum

cout << "\nThe sum is " << sum << endl;

return 0;

Output

Enter a number: 6

Enter a number: 12

Enter a number: 7

Enter a number: 0

Enter a number: -2

The sum is 25

While Loop example in C++

#include <iostream>

using namespace std;

int main(){

int i=1;

/* The loop would continue to print

* the value of i until the given condition

* i<=6 returns false.

*/
while(i<=6){

cout<<"Value of variable i is: "<<i<<endl; i++;

Output:

Value of variable i is: 1

Value of variable i is: 2

Value of variable i is: 3

Value of variable i is: 4

Value of variable i is: 5

Value of variable i is: 6

C++ do...while Loop


The do...while loop is a variant of the while loop with one
important difference: the body of do...while loop is
executed once before the condition is checked.

Its syntax is:

do {

// body of loop;

while (condition);

Here,

The body of the loop is executed at first. Then


the condition is evaluated.

If the condition evaluates to true, the body of the loop


inside the do statement is executed again.

The condition is evaluated once again.

If the condition evaluates to true, the body of the loop


inside the do statement is executed again.
This process continues until the condition evaluates to false. Then the loop stops.

Example : Display Numbers from 1 to 5

// C++ Program to print numbers from 1 to 5

#include <iostream>

using namespace std;

int main() {

int i = 1;

// do...while loop from 1 to 5

do {

cout << i << " ";

++i;

while (i <= 5);

return 0;

Output

12345

Example : Sum of Positive Numbers Only

// program to find the sum of positive numbers

// If the user enters a negative number, the loop ends

// the negative number entered is not added to the sum

#include <iostream>

using namespace std;

int main() {
int number = 0;

int sum = 0;

do {

sum += number;

// take input from the user

cout << "Enter a number: ";

cin >> number;

while (number >= 0);

// display the sum

cout << "\nThe sum is " << sum << endl;

return 0;

Output

Enter a number: 6

Enter a number: 12

Enter a number: 7

Enter a number: 0

Enter a number: -2

The sum is 25
C++ Break Statement
The C++ break is used to break loop or
switch statement. It breaks the current
flow of the program at the given
condition. In case of inner loop, it breaks
only inner loop.

jump-statement;

break;

Flowchart:

C++ Break Statement Example

Let's see a simple example of C++ break statement which is used inside the loop.

#include <iostream>

using namespace std;

int main() {

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

if (i == 5)

break;

cout<<i<<"\n";

Output:

1
2

Example – Use of break statement in a while loop

#include <iostream>

using namespace std;

int main(){

int num =10;

while(num<=200) {

cout<<"Value of num is: "<<num<<endl;

if (num==12) {

break;

num++;

cout<<"Hey, I'm out of the loop";

return 0;

Output:

Value of num is: 10

Value of num is: 11

Value of num is: 12

Hey, I'm out of the loop


Example: break statement in for loop

#include <iostream>

using namespace std;

int main(){

int var;

for (var =200; var>=10; var --) {

cout<<"var: "<<var<<endl;

if (var==197) {

break;

cout<<"Hey, I'm out of the loop";

return 0;

Output:

var: 200

var: 199

var: 198

var: 197

Hey, I'm out of the loop


Example: break statement in Switch Case

#include <iostream>

using namespace std;

int main(){

int num=2;

switch (num) {

case 1: cout<<"Case 1 "<<endl;

break;

case 2: cout<<"Case 2 "<<endl;

break;

case 3: cout<<"Case 3 "<<endl;

break;

default: cout<<"Default "<<endl;

cout<<"Hey, I'm out of the switch case";

return 0;

Output:

Case 2

Hey, I'm out of the switch case


C++ Continue Statement
The C++ continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

jump-statement;

continue;

C++ Continue Statement Example

#include <iostream>

using namespace std;

int main()

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

if(i==5){

continue;

cout<<i<<"\n";

Output:

8
9

10

Example: Use of continue in While loop

#include <iostream>

using namespace std;

int main(){

int j=6;

while (j >=0) {

if (j==4) {

j--;

continue;

cout<<"Value of j: "<<j<<endl;

j--;

return 0;

Output:

Value of j: 6

Value of j: 5

Value of j: 3

Value of j: 2

Value of j: 1

Value of j: 0
Example of continue in do-While loop

#include <iostream>

using namespace std;

int main(){

int j=4;

do {

if (j==7) {

j++;

continue;

cout<<"j is: "<<j<<endl;

j++;

}while(j<10);

return 0;

Output:

j is: 4

j is: 5

j is: 6

j is: 8

j is: 9
Program to Check Armstrong Number

#include <iostream>

using namespace std;

int main()

int origNum, num, rem, sum = 0;

cout << "Enter a positive integer: ";

cin >> origNum;

num = origNum;

while(num != 0)

digit = num % 10;

sum += digit * digit * digit;

num /= 10;

if(sum == origNum)

cout << origNum << " is an Armstrong number.";

else

cout << origNum << " is not an Armstrong number.";

return 0;

Output

Enter a positive integer: 371

371 is an Armstrong number.


goto statement in C++
The goto statement is used for transferring the control of a program to a given label. The
syntax of goto statement looks like this:

goto label_name;

Program structure:

label1:

...

...

goto label2;

...

..

label2:

...

Example of goto statement in C++

#include <iostream>

using namespace std;

int main(){

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

if (num % 2==0){

goto print;

else {

cout<<"Odd Number";

}
print:

cout<<"Even Number";

return 0;

Output:

Enter a number: 42

Even Number

Example: goto Statement

// This program calculates the average of numbers entered by the user.

// If the user enters a negative number, it ignores the number and

// calculates the average number entered before it.

# include <iostream>

using namespace std;

int main()

float num, average, sum = 0.0;

int i, n;

cout << "Maximum number of inputs: ";

cin >> n;

for(i = 1; i <= n; ++i)

cout << "Enter n" << i << ": ";

cin >> num;

if(num < 0.0)

{
// Control of the program move to jump:

goto jump;

sum += num;

jump:

average = sum / (i - 1);

cout << "\nAverage = " << average;

return 0;

Output

Maximum number of inputs: 10

Enter n1: 2.3

Enter n2: 5.6

Enter n3: -5.6

Average = 3.95

C++ Goto Statement Example

Let's see the simple example of goto statement in C++.

#include <iostream>

using namespace std;

int main()

ineligible:

cout<<"You are not eligible to vote!\n";


cout<<"Enter your age:\n";

int age;

cin>>age;

if (age < 18){

goto ineligible;

else

cout<<"You are eligible to vote!";

Output:

You are not eligible to vote!

Enter your age:

16

You are not eligible to vote!

Enter your age:

You are not eligible to vote!

Enter your age:

22

You are eligible to vote!


C++ Arrays
Like other programming languages, array in C++ is a group of similar types of elements that
have contiguous memory location.

In C++ std::array is a container that encapsulates fixed size arrays. In C++, array index
starts from 0. We can store only fixed set of elements in C++ array.

Advantages of C++ Array

Code Optimization (less code)

Random Access

Easy to traverse data

Easy to manipulate data

Easy to sort data etc.

Disadvantages of C++ Array

Fixed size

C++ Array Types

There are 2 types of arrays in C++ programming:

Single Dimensional Array

Multidimensional Array
C++ Array Declaration

dataType arrayName[arraySize];

For example,

int x[6];

Here,

int - type of element to be stored

x - name of the array

6 - size of the array

Access Elements in C++ Array

In C++, each element in an array is associated with a number. The number is known as an
array index. We can access elements of an array by using those indices.

// syntax to access array elements

array[index];

Consider the array x we have seen above.

Elements of an array in C++

Few Things to Remember:

The array indices start with 0. Meaning x[0] is the first element stored at index 0.

If the size of an array is n, the last element is stored at index (n-1). In this
example, x[5] is the last element.

Elements of an array have consecutive addresses. For example, suppose the starting
address of x[0] is 2120d. Then, the address of the next element x[1] will be 2124d, the
address of x[2] will be 2128d and so on.

Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.

C++ Array Initialization

In C++, it's possible to initialize an array during declaration. For example,

// declare and initialize and array

int x[6] = {19, 10, 8, 17, 9, 15};

C++ Array elements and their data

Another method to initialize array during declaration:

// declare and initialize an array

int x[] = {19, 10, 8, 17, 9, 15};

Here, we have not mentioned the size of the array. In such cases, the compiler
automatically computes the size.

Example: Calculate Average of Numbers Using Arrays

#include <iostream>

using namespace std;

int main()

int n, i;

float num[100], sum=0.0, average;


cout << "Enter the numbers of data: ";

cin >> n;

while (n > 100 || n <= 0)

cout << "Error! number should in range of (1 to 100)." << endl;

cout << "Enter the number again: ";

cin >> n;

for(i = 0; i < n; ++i)

cout << i + 1 << ". Enter number: ";

cin >> num[i];

sum += num[i];

average = sum / n;

cout << "Average = " << average;

return 0;

Output

Enter the numbers of data: 6

1. Enter number: 45.3

2. Enter number: 67.5

3. Enter number: -45.6

4. Enter number: 20.34

5. Enter number: 33
6. Enter number: 45.6

Average = 27.69

Example: Display Largest Element of an array

#include <iostream>

using namespace std;

int main()

int i, n;

float arr[100];

cout << "Enter total number of elements(1 to 100): ";

cin >> n;

cout << endl;

// Store number entered by the user

for(i = 0; i < n; ++i)

cout << "Enter Number " << i + 1 << " : ";

cin >> arr[i];

// Loop to store largest number to arr[0]

for(i = 1;i < n; ++i)

// Change < to > if you want to find the smallest element

if(arr[0] < arr[i])

arr[0] = arr[i];

}
cout << "Largest element = " << arr[0];

return 0;

Output

Enter total number of elements: 8

Enter Number 1: 23.4

Enter Number 2: -34.5

Enter Number 3: 50

Enter Number 4: 33.5

Enter Number 5: 55.5

Enter Number 6: 43.7

Enter Number 7: 5.7

Enter Number 8: -66.5

Largest element = 55.5

simple example of C++ array

#include <iostream>

using namespace std;

int main()

int arr[5]={10, 0, 20, 0, 30}; //creating and initializing array

//traversing array

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

{
cout<<arr[i]<<"\n";

Output

10

20

30

C++ Multidimensional Arrays


In this tutorial, we'll learn about multi-dimensional arrays in C++. More specifically, how to
declare them, access them, and use them efficiently in our program.

In C++, we can create an array of an array, known as a multidimensional array. For example:

int x[3][4];

Here, x is a two-dimensional array. It can hold a maximum of 12 elements.

We can think of this array as a table with 3 rows and each row has 4 columns as shown
below.

Elements in two-dimensional
array in C++ Programming
Three-dimensional arrays also work in a similar way. For example:

float x[2][4][3];

This array x can hold a maximum of 24 elements.

We can find out the total number of elements in the array simply by multiplying its
dimensions:

2 x 4 x 3 = 24

Multidimensional Array Initialization

Like a normal array, we can initialize a multidimensional array in more than one way.

1. Initialization of two-dimensional array

int test[2][3] = {2, 4, 5, 9, 0, 19};

The above method is not preferred. A better way to initialize this array with the same
array elements is given below:

int test[2][3] = { {2, 4, 5}, {9, 0, 19}};

This array has 2 rows and 3 columns, which is why we have two rows of elements with 3
elements each.

Initializing a two-dimensional array


in C++
Example 1: Two Dimensional Array

// C++ Program to display all elements

// of an initialised two dimensional array

#include <iostream>

using namespace std;

int main() {

int test[3][2] = {{2, -5},

{4, 0},

{9, 1}};

// use of nested for loop

// access rows of the array

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

// access columns of the array

for (int j = 0; j < 2; ++j) {

cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;

return 0;

Output

test[0][0] = 2
test[0][1] = -5

test[1][0] = 4

test[1][1] = 0

test[2][0] = 9

test[2][1] = 1

Example 2: Taking Input for Two Dimensional Array

#include <iostream>

using namespace std;

int main() {

int numbers[2][3];

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

// Storing user input in the array

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

for (int j = 0; j < 3; ++j) {

cin >> numbers[i][j];

cout << "The numbers are: " << endl;

// Printing array elements

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


for (int j = 0; j < 3; ++j) {

cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;

return 0;

Output

Enter 6 numbers:

The numbers are:

numbers[0][0]: 1

numbers[0][1]: 2

numbers[0][2]: 3

numbers[1][0]: 4

numbers[1][1]: 5

numbers[1][2]: 6
Example: Add Two Matrices using Multi-dimensional Arrays

#include <iostream>

using namespace std;

int main()

int r, c, a[100][100], b[100][100], sum[100][100], i, j;

cout << "Enter number of rows (between 1 and 100): ";

cin >> r;

cout << "Enter number of columns (between 1 and 100): ";

cin >> c;

cout << endl << "Enter elements of 1st matrix: " << endl;

// Storing elements of first matrix entered by user.

for(i = 0; i < r; ++i)

for(j = 0; j < c; ++j)

cout << "Enter element a" << i + 1 << j + 1 << " : ";

cin >> a[i][j];

// Storing elements of second matrix entered by user.

cout << endl << "Enter elements of 2nd matrix: " << endl;
for(i = 0; i < r; ++i)

for(j = 0; j < c; ++j)

cout << "Enter element b" << i + 1 << j + 1 << " : ";

cin >> b[i][j];

// Adding Two matrices

for(i = 0; i < r; ++i)

for(j = 0; j < c; ++j)

sum[i][j] = a[i][j] + b[i][j];

// Displaying the resultant sum matrix.

cout << endl << "Sum of two matrix is: " << endl;

for(i = 0; i < r; ++i)

for(j = 0; j < c; ++j)

cout << sum[i][j] << " ";

if(j == c - 1)

cout << endl;

return 0;

Output

Enter number of rows (between 1 and 100): 2


Enter number of columns (between 1 and 100): 2

Enter elements of 1st matrix:

Enter element a11: -4

Enter element a12: 5

Enter element a21: 6

Enter element a22: 8

Enter elements of 2nd matrix:

Enter element b11: 3

Enter element b12: -9

Enter element b21: 7

Enter element b22: 2

Sum of two matrix is:

-1 -4

13 10

Example: Find Transpose of a Matrix

#include <iostream>

using namespace std;

int main() {

int a[10][10], transpose[10][10], row, column, i, j;

cout << "Enter rows and columns of matrix: ";


cin >> row >> column;

cout << "\nEnter elements of matrix: " << endl;

// Storing matrix elements

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

for (int j = 0; j < column; ++j) {

cout << "Enter element a" << i + 1 << j + 1 << ": ";

cin >> a[i][j];

// Printing the a matrix

cout << "\nEntered Matrix: " << endl;

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

for (int j = 0; j < column; ++j) {

cout << " " << a[i][j];

if (j == column - 1)

cout << endl << endl;

// Computing transpose of the matrix

for (int i = 0; i < row; ++i)

for (int j = 0; j < column; ++j) {

transpose[j][i] = a[i][j];
}

// Printing the transpose

cout << "\nTranspose of Matrix: " << endl;

for (int i = 0; i < column; ++i)

for (int j = 0; j < row; ++j) {

cout << " " << transpose[i][j];

if (j == row - 1)

cout << endl << endl;

return 0;

Output

Enter rows and columns of matrix: 2

Enter elements of matrix:

Enter element a11: 1

Enter element a12: 2

Enter element a13: 9

Enter element a21: 0

Enter element a22: 4

Enter element a23: 7

Entered Matrix:
1 2 9

0 4 7

Transpose of Matrix:

1 0

2 4

9 7

C++ Strings
In this tutorial, you'll learn to handle strings in C++. You'll learn to declare them, initialize
them and use them for various input/output operations.

String is a collection of characters. There are two types of strings commonly used in C++
programming language:

Strings that are objects of string class (The Standard C++ Library string class)

C-strings (C-style Strings)

C-strings

In C programming, the collection of characters is stored in the form of arrays. This is also
supported in C++ programming. Hence it's called C-strings.

C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value
of null character is 0).
How to define a C-string?

char str[] = "C++";

In the above code, str is a string and it holds 4 characters.

Although, "C++" has 3 character, the null character \0 is added to the end of the string
automatically.

Alternative ways of defining a string

char str[4] = "C++";

char str[] = {'C','+','+','\0'};

char str[4] = {'C','+','+','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char str[100] = "C++";

Example 1: C++ String to read a word

C++ program to display a string entered by user.

#include <iostream>

using namespace std;

int main()

char str[100];

cout << "Enter a string: ";

cin >> str;

cout << "You entered: " << str << endl;


cout << "\nEnter another string: ";

cin >> str;

cout << "You entered: "<<str<<endl;

return 0;

Output

Enter a string: C++

You entered: C++

Enter another string: Programming is fun.

You entered: Programming

Notice that, in the second example only "Programming" is displayed instead of


"Programming is fun".

This is because the extraction operator >> works as scanf() in C and considers a space " "
has a terminating character.

Example 2: C++ String to read a line of text

C++ program to read and display an entire line entered by user.

#include <iostream>

using namespace std;

int main()

char str[100];

cout << "Enter a string: ";


cin.get(str, 100);

cout << "You entered: " << str << endl;

return 0;

Output

Enter a string: Programming is fun.

You entered: Programming is fun.

Example 1: Find Frequency of Characters of a String Object

#include <iostream>

using namespace std;

int main()

string str = "C++ Programming is awesome";

char checkCharacter = 'a';

int count = 0;

for (int i = 0; i < str.size(); i++)

if (str[i] == checkCharacter)

++ count;

}
cout << "Number of " << checkCharacter << " = " << count;

return 0;

Output

Number of a = 2

Example 1: Remove all characters except alphabets

This program takes a string (object) input from the user and removes all characters
except alphabets.

#include <iostream>

using namespace std;

int main() {

string line;

string temp = "";

cout << "Enter a string: ";

getline(cin, line);

for (int i = 0; i < line.size(); ++i) {

if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z')) {

temp = temp + line[i];

}
line = temp;

cout << "Output String: " << line;

return 0;

Output

Enter a string: p2'r"o@gram84iz./

Output String: programiz

Example: Length of String Object

#include <iostream>

using namespace std;

int main() {

string str = "C++ Programming";

// you can also use str.length()

cout << "String Length = " << str.size();

return 0;

Output

String Length = 15
Example 1: Concatenate String Objects

#include <iostream>

using namespace std;

int main()

string s1, s2, result;

cout << "Enter string s1: ";

getline (cin, s1);

cout << "Enter string s2: ";

getline (cin, s2);

result = s1 + s2;

cout << "Resultant String = "<< result;

return 0;

Output

Enter string s1: C++ Programming

Enter string s2: is awesome.

Resultant String = C++ Programming is awesome.


Example 1: From a C-style string

This program takes a C-style string from the user and calculates the number of vowels,
consonants, digits and white-spaces.

#include <iostream>

using namespace std;

int main()

char line[150];

int vowels, consonants, digits, spaces;

vowels = consonants = digits = spaces = 0;

cout << "Enter a line of string: ";

cin.getline(line, 150);

for(int i = 0; line[i]!='\0'; ++i)

if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||

line[i]=='o' || line[i]=='u' || line[i]=='A' ||

line[i]=='E' || line[i]=='I' || line[i]=='O' ||

line[i]=='U')

++vowels;

else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))

++consonants;
}

else if(line[i]>='0' && line[i]<='9')

++digits;

else if (line[i]==' ')

++spaces;

cout << "Vowels: " << vowels << endl;

cout << "Consonants: " << consonants << endl;

cout << "Digits: " << digits << endl;

cout << "White spaces: " << spaces << endl;

return 0;

Output

Enter a line of string: This is 1 hell of a book.

Vowels: 7

Consonants: 10

Digits: 1

White spaces: 6
C++ Functions
A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it. We can create two
functions to solve this problem:

a function to draw the circle

a function to color the circle

Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.

There are two types of function:

Standard Library Functions: Predefined in C++

User-defined Function: Created by users

In this tutorial, we will focus mostly on user-defined functions.

C++ User-defined Function

C++ allows the programmer to define their own function.

A user-defined function groups code to perform a specific task and that group of code is
given a name (identifier).

When the function is invoked from any part of the program, it all executes the codes
defined in the body of the function.

C++ Function Declaration

The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {

// function body

Here's an example of a function declaration.

// function declaration
void greet() {

cout << "Hello World";

Here,

the name of the function is greet()

the return type of the function is void

the empty parentheses mean it doesn't have any parameters

the function body is written inside {}

Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function

In the above program, we have declared a function named greet(). To use


the greet() function, we need to call it.

Here's how we can call the above greet() function.

int main() {

// calling a function

greet();

}
How Function works in C++

Example 1: Display a Text

#include <iostream>

using namespace std;

// declaring a function

void greet() {

cout << "Hello there!";

int main() {

// calling the function

greet();

return 0;

}
Output

Hello there!

Function Parameters

As mentioned above, a function can be declared with parameters (arguments). A parameter


is a value that is passed when declaring a function.

For example, let us consider the function below:

void printNum(int num) {

cout << num;

Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.

int main() {

int n = 7;

// calling the function

// n is passed to the function as argument

printNum(n);

return 0;

Example 2: Function with Parameters

// program to print a text

#include <iostream>

using namespace std;


// display a number

void displayNum(int n1, float n2) {

cout << "The int number is " << n1;

cout << "The double number is " << n2;

int main() {

int num1 = 5;

double num2 = 5.5;

// calling the function

displayNum(num1, num2);

return 0;

Output

The int number is 5

The double number is 5.5

In the above program, we have used a function that has one int parameter and
one double parameter.

We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.
C++ function
with parameters

Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.

Return Statement

In the above programs, we have used void in the function declaration. For example,

void displayNumber() {

// code

This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.

Then, the return statement can be used to return a value from a function.

For example,

int add (int a, int b) {

return (a + b);

Here, we have the data type int instead of void. This means that the function returns
an int value.
The code return (a + b); returns the sum of the two parameters as the function value.

The return statement denotes that the function has ended. Any code after return inside
the function is not executed.

Example 3: Add Two Numbers

// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function

int add(int a, int b) {

return (a + b);

int main() {

int sum;

// calling the function and storing

// the returned value in sum

sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two numbers.

We pass two int literals 100 and 78 while calling the function.

We store the returned value of the function in the variable sum, and then we print it.

Working of
C++ Function with return statement

Notice that sum is a variable of int type. This is because the return value of add() is
of int type.

Function Prototype

In C++, the code of function declaration should be before the function call. However, if we
want to define a function after the function call, we need to use the function prototype.
For example,

// function prototype

void add(int, int);

int main() {
// calling the function before declaration.

add(5, 3);

return 0;

// function definition

void add(int a, int b) {

cout << (a + b);

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name and its parameters.
That's why we can use the code to call a function before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);

Example 4: C++ Function Prototype

// using function definition after main() function

// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype

int add(int, int);


int main() {

int sum;

// calling the function and storing

// the returned value in sum

sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;

// function definition

int add(int a, int b) {

return (a + b);

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is that here, the
function is defined after the function call.

That's why we have used a function prototype in this example.

Benefits of Using User-Defined Functions

Functions make the code reusable. We can declare them once and use them multiple times.

Functions make the program easier as each small task is divided into a function.

Functions increase readability.


C++ Library Functions

Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions directly; they don't need
to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.

In order to use library functions, we usually need to include the header file in which these
library functions are defined.

For instance, in order to use mathematical functions such as sqrt() and abs(), we need to
include the header file cmath.

Example 5: C++ Program to Find the Square Root of a Number

#include <iostream>

#include <cmath>

using namespace std;

int main() {

double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root

squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;

}
Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root of a
number.

The function declaration of sqrt() is defined in the cmath header file. That's why we need
to use the code #include <cmath> to use the sqrt() function.

Types of User-defined Functions in C++

For better understanding of arguments and return in functions, user-defined functions can
be categorised as:

Function with no argument and no return value

Function with no argument but return value

Function with argument but no return value

Function with argument and return value

Consider a situation in which you have to check prime number. This problem is solved below
by making user-defined function in 4 different ways as mentioned above.

Example 1: No arguments passed and no return value

# include <iostream>

using namespace std;

void prime();

int main()

// No argument is passed to prime()

prime();

return 0;

}
// Return type of function is void because value is not returned.

void prime()

int num, i, flag = 0;

cout << "Enter a positive integer enter to check: ";

cin >> num;

for(i = 2; i <= num/2; ++i)

if(num % i == 0)

flag = 1;

break;

if (flag == 1)

cout << num << " is not a prime number.";

else

{
cout << num << " is a prime number.";

In the above program, prime() is called from the main() with no arguments.

prime() takes the positive number from the user and checks whether the number is a
prime number or not.

Since, return type of prime() is void, no value is returned from the function.

Example 2: No arguments passed but a return value

#include <iostream>

using namespace std;

int prime();

int main()

int num, i, flag = 0;

// No argument is passed to prime()

num = prime();

for (i = 2; i <= num/2; ++i)

if (num%i == 0)

flag = 1;

break;

}
}

if (flag == 1)

cout<<num<<" is not a prime number.";

else

cout<<num<<" is a prime number.";

return 0;

// Return type of function is int

int prime()

int n;

printf("Enter a positive integer to check: ");

cin >> n;

return n;

In the above program, prime() function is called from the main() with no arguments.

prime() takes a positive integer from the user. Since, return type of the function is an int,
it returns the inputted number from the user back to the calling main() function.
Then, whether the number is prime or not is checked in the main() itself and printed onto
the screen.

Example 3: Arguments passed but no return value

#include <iostream>

using namespace std;

void prime(int n);

int main()

int num;

cout << "Enter a positive integer to check: ";

cin >> num;

// Argument num is passed to the function prime()

prime(num);

return 0;

// There is no return value to calling function. Hence, return type of function is void. */

void prime(int n)

int i, flag = 0;

for (i = 2; i <= n/2; ++i)

if (n%i == 0)
{

flag = 1;

break;

if (flag == 1)

cout << n << " is not a prime number.";

else {

cout << n << " is a prime number.";

In the above program, positive number is first asked from the user which is stored in the
variable num.

Then, num is passed to the prime() function where, whether the number is prime or not is
checked and printed.

Since, the return type of prime() is a void, no value is returned from the function.

Example 4: Arguments passed and a return value.

#include <iostream>

using namespace std;

int prime(int n);

int main()
{

int num, flag = 0;

cout << "Enter positive integer to check: ";

cin >> num;

// Argument num is passed to check() function

flag = prime(num);

if(flag == 1)

cout << num << " is not a prime number.";

else

cout<< num << " is a prime number.";

return 0;

/* This function returns integer value. */

int prime(int n)

int i;

for(i = 2; i <= n/2; ++i)

if(n % i == 0)

return 1;

return 0;
}

C++ OOPs Concepts


The major purpose of C++ programming is to introduce the concept of object orientation to the
C programming language.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is known as truly


object-oriented programming language. Smalltalk is considered as the first truly object-
oriented programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by providing some concepts:

o Object

o Class

o Inheritance
o Polymorphism

o Abstraction

o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.

In C++, we use Function overloading and Function overriding to achieve polymorphism.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object of student class using s1 as the reference variable.

1. Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers to the
instance of Student class.

C++ Class
In C++, object is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C++ class that has three fields only.

1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
 Write a program to create a class Student having following data members:
1) Name 2)Roll No 3)Percentage for one Student

#include<iostream>
using namespace std;
class Student
{
private:
char name[30];
int rollno;
float per;
public:
void getdata()
{
cout<<"Enter Name:";
cin>>name;
cout<<"Enter RollNo:";
cin>>rollno;
cout<<"Enter Per:";
cin>>per;

}
void putdata()
{
cout<<"Display Student Data:\n";
cout<<"\nName:"<<name;
cout<<"\nRoll no.:"<<rollno;
cout<<"\nPercentage:"<<per;
}
};
int main()
{
Student s1;
s1.getdata();
s1.putdata();
return 0;
}
 Write a program to create a class Employee having following data members:
1) Emp_Name 2)Emp_Id 3)Salary for one Employee

#include<iostream>
using namespace std;
class Employee
{
private:
char Emp_Name[30];
int Emp_Id;
float Salary;
public:
void getdata()
{
cout<<”Enter Employee Data”;
cout<<"Enter Employee Name:";
cin>>Emp_Name;
cout<<"Enter Employee Id:";
cin>>Emp_Id;
cout<<"Enter Employee Salary:";
cin>>Salary;

}
void putdata()
{
cout<<"Display Employee Data:\n";
cout<<"\nEmp_Name:"<<Emp_Name;
cout<<"\nEmp_Id:"<<Emp_Id;
cout<<"\nSalary:"<<Salary;
}
};
int main()
{
Employee e1;
e1.getdata();
e1.putdata();
return 0;
}
 Write a program to create a class Book having following data members:
1) Book_Name 2)Author3)Price for one Book
#include<iostream>
using namespace std;
class Book
{
private:
char Book_Name[30];
char Author[30];
float Price;
public:
void getdata()
{
cout<<"Enter Book Data\n";
cout<<"Enter Book Name:";
cin>> Book_Name;
cout<<"Enter Author Name :";
cin>>Author;
cout<<"Enter Book Price:";
cin>>Price;

}
void putdata()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
}
};
int main()
{
Book b1;
b1.getdata();
b1.putdata();
return 0;
}
 Write a program to create a class Student having following data members:
1) Name 2)Roll No 3)Percentage for two Student

#include<iostream>
using namespace std;
class Student
{
private:
char name[30];
int rollno;
float per;
public:
void getdata()
{
cout<<"\nEnter Name:";
cin>>name;
cout<<"Enter RollNo:";
cin>>rollno;
cout<<"Enter Per:";
cin>>per;

}
void display()
{
cout<<"Display Student Data:\n";
cout<<"\nName:"<<name;
cout<<"\nRoll no.:"<<rollno;
cout<<"\nPercentage:\n"<<per;
}
};
int main()
{
Student s1,s2;
s1.getdata();
s1.display();
s2.getdata();
s2.display();
return 0;
}
 Write a program to create a class Book having following data members:
1) Book_Name 2)Author3)Price 4)Page No 5)Year for two Book
#include<iostream>
using namespace std;
class Book
{
private:
char Book_Name[30];
char Author[30];
float Price;
int Page_No;
int year;
public:
void getdata()
{
cout<<"Enter Book Data\n";
cout<<"Enter Book Name:";
cin>> Book_Name;
cout<<"Enter Author Name :";
cin>>Author;
cout<<"Enter Book Price:";
cin>>Price;
cout<<"Enter Page No:";
cin>>Page_No;
cout<<"Enter Book Publish Year:";
cin>>year;
}
void putdata()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
cout<<"\nPage No:"<<Page_no;
cout<<"\nPublish Year:"<<year;
}
};
int main()
{
Book b1,b2;
b1.getdata();
b1.putdata();
b2.getdata();
b2.putdata();
return 0;
}

 Write a program to create a class Employee having following data members:


1) Emp_Name 2)Emp_Id 3)Salary for ten Employee

#include<iostream>
using namespace std;
class Employee
{
private:
char Emp_Name[30];
int Emp_Id;
float Salary;
public:
void getdata()
{
cout<<”Enter Employee Data”;
cout<<"Enter Employee Name:";
cin>>Emp_Name;
cout<<"Enter Employee Id:";
cin>>Emp_Id;
cout<<"Enter Employee Salary:";
cin>>Salary;
}
void display()
{
cout<<"Display Employee Data:\n";
cout<<"\nEmp_Name:"<<Emp_Name;
cout<<"\nEmp_Id:"<<Emp_Id;
cout<<"\nSalary:"<<Salary;
}
};
int main()
{
Employee e[10];
int i;
for(i=1;i<=10;i++)
{
e[i].getdata();
}
for(i=1;i<=10;i++)
{
e[i].display();
}
Return 0;
}

 Write a program to create a class Book having following data members:


1) Book_Name 2)Author3)Price for five Book
#include<iostream>
using namespace std;
class Book
{
private:
char Book_Name[30];
char Author[30];
float Price;
public:
void getdata()
{
cout<<"Enter Book Data\n";
cout<<"Enter Book Name:";
cin>> Book_Name;
cout<<"Enter Author Name :";
cin>>Author;
cout<<"Enter Book Price:";
cin>>Price;

}
void display()
{
cout<<"\nDisplay Book Data:\n";
cout<<"\nBook Name:"<<Book_Name;
cout<<"\nAuthor:"<<Author;
cout<<"\nPrice:"<<Price;
}
};
int main()
{
Book b[5];
int i;
for(i=1;i<=5;i++)
{
b[i].getdata();
}
for(i=1;i<=5;i++)
{
b[i].display();
}
Return 0;
}

C++ Constructor
A Constructor is a special member function for automatic initialization of an object.

They have same name as class name. There can be any number of overloaded constructor inside
a class provided they have a different sets of parameters.

Rules for Writing a Constructor

 Constructor have the same name as class


 Constructor do not return any value
 They cannot be inherited
 Cannot refers to address
 They can have default argument
Syntax

class user_name

Private:

……………

…………….

protected:

…………….

…………………

public:

user_name(); //Constructor Declare

………..

…………

};

user_name::user_name() //Constructor defined

……….

……………

}
Example:-

class Rectangle

int width,height;

public:

Rectangle(); //constructor declared

int area(void);

};

Rectangle::Rectangle()

…………..

……………

Types of Constructor

1) Default Constructor
2) Parameterized Constructor
3) Copy Constructor
4) Dynamic Constructor
1) Default Constructor: - A constructor which has no argument is known
as default constructor. It is invoked at the time of creating object.

Syntax:
className( );

Program for default constructor

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

public:

// create a constructor

Wall() {

// initialize private variables

length = 5.5;

cout << "Creating a wall." << endl;

cout << "Length = " << length << endl;

};

int main() {

// create an object

Wall wall1;

return 0;

}
Program for default constructor
#include <iostream>
using namespace std;

class construct
{
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;

return 0;

2) Parameterized Constructor:- It is possible to pass arguments to


constructors. Typically, these arguments help initialize an object when it is
created. To create a parameterized constructor, simply add parameters to
it the way you would to any other function.
Eg:-
XYZ(int a, int b)
{

}
...
XYZ obj(10, 20);

Program for Parameterized constructor

#include <iostream>
using namespace std;
class Add{
public:
//Parameterized constructor
Add(int num1, int num2) {
cout<<(num1+num2)<<endl;
}
};
int main(void){

Add obj1(10, 20);

Add obj2 = Add(50, 60);


return 0;
}

Program for Parameterized constructor

#include <iostream>

using namespace std;

// declare a class

class Wall {

private:

double length;

double height;
public:

// create parameterized constructor

Wall(double len, double hgt) {

// initialize private variables

length = len;

height = hgt;

double calculateArea() {

return length * height;

};

int main() {

// create object and initialize data members

Wall wall1(10.5, 8.6);

Wall wall2(8.5, 6.3);

cout << "Area of Wall 1: " << wall1.calculateArea() << endl;

cout << "Area of Wall 2: " << wall2.calculateArea() << endl;

return 0;

3) Copy Constructor:- Copy Constructors is a type of constructor which is used


to create a copy of an already existing object of a class type. It is usually of the
form X (X&), where X is the class name. The compiler provides a default Copy
Constructor to all the classes.
Syntax:-

Classname(const classname &objectname)

....

Program for Copy constructor

#include<iostream>

using namespace std;

class copyconstructor

private:

int x, y; //data members

public:

copyconstructor(int x1, int y1)

x = x1;

y = y1;

/* Copy constructor */

copyconstructor (const copyconstructor &sam)

x = sam.x;

y = sam.y;

}
void display()

cout<<x<<" "<<y<<endl;

};

int main()

copyconstructor obj1(10, 15); // Normal constructor

copyconstructor obj2 = obj1; // Copy constructor

cout<<"Normal constructor : ";

obj1.display();

cout<<"Copy constructor : ";

obj2.display();

return 0;

Program for Copy constructor

#include <iostream>

Using namespace std;

class Date

public:

int day, month, year;

Date()

{
cout<<”\n Default Constructor:”;

day=15;

month=12;

year=2013;

Date(int d, int m, int y)

cout<<”\n Copy Constructor:\n”;

day=d;

month=m;

year=y;

void show()

cout<<”\nDay:”<<day<<”\nMonth:”<<month<<”\nYear:”<<year;

};

int main()

Date d;

d.show();
Date d1(07,12,1996);

d1.show();

4) Dynamic Constructor:-The constructor can also be used to allocate memory


while creating objects. This will enable the system to allocate the right amount of
memory for each object. Allocation of memory to objects at the time of their
construction is known as dynamic construction of objects. The memory is
allocated with the help of the new operator.

Program for Dynamic constructor

#include<iostream>

#include<string.h>

using namespace std;

class Sample

char *name;

int length;

public:

Sample( )

length = 0;

name = new char[ length + 1];

}
Sample ( char *s )

length = strlen(s);

name = new char[ length + 1 ];

strcpy( name , s );

void display( )

cout<<name<<endl;

};

int main( )

char *first = "C++";

Sample S1(first), S2("ABC"), S3("XYZ");

S1.display( );

S2.display( );

S3.display( );

return 0;

}
Program for Dynamic constructor

#include<iostream>

#include<cstring>

using namespace std;

class String

char *name;

int length;

public :

String ()

length=0;

name=new char[length+1];

String (char *s) // constructor 2

length=strlen(s);

name=new char[length+1]; //one additional

strcpy(name,s); // character for \0

void display()
{

std::cout<<name <<"\n";

void join(String &a,String &b);

}; void String:: join(String &a,String &b)

length=a.length+b.length;

delete name;

name=new char[length+1]; // dynamic allocation

strcpy(name,a.name);

strcat(name,b.name);

};

int main()

char *first="C++";

String name1(first),name2("Programming"),name3("Awesome"),s1,s2;

s1.join(name1,name2);

s2.join(s1,name3);

name1.display();

name2.display();

name3.display();
s1.display();

s2.display();

Overloading Constructor

 Overloaded constructors must have the same name and different number of
arguments
 The constructor is called based on the number and types of the arguments
are passed.
 We have to pass the argument while creating objects, otherwise the
constructor cannot understand which constructor will be called.
Example
#include <iostream>

using namespace std;

class Rect{

private:

int area;

public:

Rect(){

area = 0;

Rect(int a, int b){

area = a * b;

void display(){
cout << "The area is: " << area << endl;

};

main(){

Rect r1;

Rect r2(2, 6);

r1.display();

r2.display();

Output
The area is: 0
The area is: 12

Dynamic initialization of object


#include <iostream>
using namespace std;
class simple_interest
{
float principle , time, rate ,interest;

public:
simple_interest (float a, float b, float c) {
principle = a;
time =b;
rate = c;
}
void display ( ) {
interest =(principle* rate* time)/100;
cout<<"interest ="<<interest ;
}
};

int main(){
float p,r,t;
cout<<"principle amount, time and rate"<<endl;
cout<<"2000 7.5 2"<<endl;
simple_interest s1(2000,7.5,2);//dynamic initialization
s1.display();
return 0;
}

Dynamic initialization of object

#include <iostream>

using namespace std;

//structure definition with private and public members

class Student {

private:

int rNo;

float perc;

public:

//constructor

Student(int r, float p)

rNo = r;

perc = p;

//function to read details

void read(void)

{
cout << "Enter roll number: ";

cin >> rNo;

cout << "Enter percentage: ";

cin >> perc;

//function to print details

void print(void)

cout << endl;

cout << "Roll number: " << rNo << endl;

cout << "Percentage: " << perc << "%" << endl;

};

//Main code

int main()

//reading roll number and percentage to initialize

//the members while creating object

cout << "Enter roll number to initialize the object: ";

int roll_number;

cin >> roll_number;

cout << "Enter percentage to initialize the object: ";

float percentage;

cin >> percentage;


//declaring and initialize the object

struct Student std(roll_number, percentage);

//print the value

cout << "After initializing the object, the values are..." << endl;

std.print();

//reading and printing student details

//by calling public member functions of the structure

std.read();

std.print();

return 0;

Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.

A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).

Rules for Writing a Constructor

 The destructor must have the same name as the class name
with a tilde(~) prefix.
 It never takes any arguments and no return value.
 It cannot be declared as static volatile and constant
 It takes no argument and therefore cannot be overloaded
 It should have public access in the class declaration.
Syntax:-

~className();

Program for Destructor

#include <iostream>

using namespace std;

class Employee

public:

Employee()

cout<<"Constructor Invoked"<<endl;

~Employee()

cout<<"Destructor Invoked"<<endl;

};

int main(void)

Employee e1; //creating an object of Employee


Employee e2; //creating an object of Employee

return 0;

Program for Destructor


#include <iostream>
using namespace std;
class HelloWorld{
public:
//Constructor
HelloWorld(){
cout<<"Constructor is called"<<endl;
}
//Destructor
~HelloWorld(){
cout<<"Destructor is called"<<endl;
}
//Member function
void display(){
cout<<"Hello World!"<<endl;
}
};
int main(){
//Object created
HelloWorld obj;
//Member function called
obj.display();
return 0;
}
Program for Destructor
#include <iostream>
using namespace std;
class A
{
int num;
static int count;
public:
//Constructor
A(int n=0);
//Destructor
~A();
static int getcount();
};
int A::count=0;
A::A(int n)
{
num=n;
count++;
cout<<"Object Created with value"<<num<<endl;
}
A::~A()
{
--count;
cout<<"Object is destroyed"<<endl;
}
int A::getcount()
{
return count;
}
int main()
{
A a1,a2(60);
cout<<"total object="<<A::getcount()<<endl;
A a3(100);
cout<<"Total objects="<<A::getcount()<<endl;
return 0;
}
C++ Inheritance
In C++, inheritance is a process in which one object acquires all the properties and behaviors of
its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviors which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.

Advantage of C++ Inheritance


Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So less code is required in the class.

Types Of Inheritance
C++ supports five types of inheritance:

o Single inheritance

o Multiple inheritance

o Hierarchical inheritance

o Multilevel inheritance

o Hybrid inheritance
Derived Classes
A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are
publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members of the
base class becomes the private members of the derived class. Therefore, the public
members of the base class are not accessible by the objects of the derived class only
by the member functions of the derived class.

o When the base class is publicly inherited by the derived class, public members of the
base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as
by the member functions of the base class.

C++ Single Inheritance


Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.
Where 'A' is the base class, and 'B' is the derived class.

C++ Single Level Inheritance Example: Inheriting


Fields
When one class inherits another class, it is known as single level inheritance. Let's see the
example of single level inheritance which inherits the fields only.

#include <iostream>
using namespace std;
class Account {
public:
float salary = 60000;
};
class Programmer: public Account {
public:
float bonus = 5000;
};
int main(void) {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}

Example:-

#include <iostream>
using namespace std;
class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};

class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
b.display();
return 0;
}

C++ Multilevel Inheritance


Multilevel inheritance is a process of deriving a class from another derived class.
C++ Multi Level Inheritance Example
When one class inherits another class which is further inherited by another class, it is known
as multi level inheritance in C++. Inheritance is transitive so the last derived class acquires all
the members of all its base classes.

Let's see the example of multi level inheritance in C++.

#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// first sub_class derived from class vehicle


class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler{
public:
car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};

// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}

Multilevel Inheritance Example:-

#include <iostream>

using namespace std;

class base {

public:

int m;

void getdata ()

cout << "Enter the value of m = "; cin >> m;

};

class derive1 : public base {

public:

int n;

void readdata ()

cout << "Enter the value of n = "; cin >> n;

};
class derive2 : public derive1

private:

int o;

public:

void indata()

cout << "Enter the value of o = "; cin >> o;

void product()

cout << "Product = " << m * n * o;

};

int main ()

derive2 p;

p.getdata();

p.readdata();

p.indata();

p.product();
return 0;

Multilevel inheritance example:

#include<iostream>

using namespace std;

class student

protected:

int rollno;

public:

void get_no(int);

void put_no(void);

};

void student::get_no(int a)

rollno=a;

void student::put_no()

cout<<"RollNO:"<<rollno<<"\n";

}
class test:public student

protected:

float sub1;

float sub2;

public:

void get_marks(float,float);

void put_marks(void);

};

void test::get_marks(float x,float y)

sub1=x;

sub2=y;

void test::put_marks()

cout<<"Marks in Sub1="<<sub1<<"\n";

cout<<"Marks in sub2="<<sub2<<"\n";

class result:public test


{

float total;

public:

void display(void);

};

void result::display(void)

total=sub1+sub2;

put_no();

put_marks();

cout<<"Total="<<total<<"\n";

int main()

result S1;

S1.get_no(111);

S1.get_marks(75,89);

S1.display();

return 0;

}
C++ Multiple Inheritance
Multiple inheritance is the process of deriving a new class that inherits the attributes from
two or more classes.

Syntax of the Derived class:

1. class D : visibility B-1, visibility B-2, ?


2. {
3. // Body of the class;
4. }

Let's see a simple example of multiple inheritance.

#include <iostream>

using namespace std;

class A

protected:

int a;

public:

void get_a(int n)

{
a = n;

};

class B

protected:

int b;

public:

void get_b(int n)

b = n;

};

class C : public A,public B

public:

void display()

std::cout << "The value of a is : " <<a<< std::endl;

std::cout << "The value of b is : " <<b<< std::endl;


cout<<"Addition of a and b is : "<<a+b;

};

int main()

C c;

c.get_a(10);

c.get_b(20);

c.display();

return 0;

Let's see a simple example of multiple inheritance. #include <iostream>

using namespace std;

// first base class

class Vehicle {

public:

Vehicle()

cout << "This is a Vehicle" << endl;


}

};

// second base class

class FourWheeler {

public:

FourWheeler()

cout << "This is a 4 wheeler Vehicle" << endl;

};

// sub class derived from two base classes

class Car: public Vehicle, public FourWheeler {

};

// main function

int main()

// creating object of sub class will

// invoke the constructor of base classes

Car obj;
return 0;

C++ Hybrid Inheritance


Hybrid inheritance is a combination of more than one type of inheritance.

Let's see a simple example:

#include <iostream>

using namespace std;

class A

protected:

int a;

public:

void get_a()
{

std::cout << "Enter the value of 'a' : " << std::endl;

cin>>a;

};

class B : public A

protected:

int b;

public:

void get_b()

std::cout << "Enter the value of 'b' : " << std::endl;

cin>>b;

};

class C

protected:

int c;
public:

void get_c()

std::cout << "Enter the value of c is : " << std::endl;

cin>>c;

};

class D : public B, public C

protected:

int d;

public:

void mul()

get_a();

get_b();

get_c();

std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;

};
int main()

D d;

d.mul();

return 0;

#include <iostream>

using namespace std;

class ClassA {

public:

int a;

};

class ClassB : public ClassA {

public:

int b;

};

class ClassC : public ClassA {

public:

int c;

};
class ClassD : public ClassB, public ClassC {

public:

int d;

};

int main()

ClassD obj;

// obj.a = 10; //Statement 1, Error

// obj.a = 100; //Statement 2, Error

obj.ClassB::a = 10; // Statement 3

obj.ClassC::a = 100; // Statement 4

obj.b = 20;

obj.c = 30;

obj.d = 40;

cout << "\n A from ClassB : " << obj.ClassB::a;

cout << "\n A from ClassC : " << obj.ClassC::a;

cout << "\n B : " << obj.b;

cout << "\n C : " << obj.c;


cout << "\n D : " << obj.d;

return 0;

Let's see a simple example:

#include<iostream>

#include<conio.h>

class student

protected:

int rollnum;

public:

void set_rollnum(int num)

rollnum=num;

void print_rollnum(void)

{
std::cout<<"Roll number is : "<<rollnum<<"\n";

};

class subject:public student

protected:

float subject1, subject2, subject3;

public:

void set_subjectmark(float a,float b,float c)

subject1 = a;

subject2 = b;

subject3 = c;

void print_subjectmarks()
{

std::cout<<"subject marks in each subject is :


"<<"subject1="<<subject1<<"\n"<<"subject2="<<subject2<<"\n"<<"subject3="<<subject3<<"\n";

};

class sports

protected:

float sport_marks;

public:

void set_sports_marks(float marks)

sport_marks=marks;

void print_sports_marks(void)

std::cout<<"marks in sports is : "<< sport_marks <<"\n";


}

};

class overall_result: public subject , public sports

private:

float total_marks;

public:

void display_total(void);

};

void overall_result::display_total(void)

total_marks=subject1+subject2+subject3+sport_marks;

print_rollnum();

print_subjectmarks();

print_sports_marks();

std::cout<<"Total marks including subject marks and sports marks is : =


"<<total_marks<<"\n";

int main()

{
overall_result stu;

stu.set_rollnum(40);

stu.set_subjectmark(19.8,34.6,89.7);

stu.set_sports_marks(64.3);

stu.display_total();

std::cout << "---------------------------------------------------------"<<"\n";

overall_result stu2;

stu2.set_rollnum(50);

stu2.set_subjectmark(10.8,54.6,59.7);

stu2.set_sports_marks(94.3);

stu2.display_total();

return 0;

C++ Hierarchical Inheritance


Hierarchical inheritance is defined as the process of deriving more than one class from a base
class.

Syntax of Hierarchical inheritance:


class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

Examples of Hierarchical Inheritance in C++


#include <iostream>

using namespace std;

class X

public:

int a, b;

void getdata ()

cout << "\nEnter value of a and b:\n"; cin >> a >> b;

}
};

class Y : public X

public:

void product()

cout << "\nProduct= " << a * b;

};

class Z: public X {

public:

void sum()

cout << "\nSum= " << a + b;

};

int main()

Y obj1;

Z obj2;

obj1.getdata();
obj1.product();

obj2.getdata();

obj2.sum();

return 0;

Example:-

#include<iostream>

using namespace std;

class A

public:

int x,y;

void getdata()

cout<<"\nEnter the value of x & y:";

cin>>x>>y;

};

class B:public A

public:
void product()

cout<<"\n Product="<<x*y;

};

class C:public A

public:

void sum()

cout<<"\nSum="<<x+y;

};

class D:public A

public:

void sub()

cout<<"\nSub="<<x-y;

};
int main()

B obj1;

C obj2;

D obj3;

obj1.getdata();

obj1.product();

obj2.getdata();

obj2.sum();

obj3.getdata();

obj3.sub();

return 0;

What are Pointers?


In C++, a pointer refers to a variable that holds the address of another
variable. Like regular variables, pointers have a data type. For example, a
pointer of type integer can hold the address of a variable of type integer.
A pointer of character type can hold the address of a variable of
character type.

Pointer Declaration Syntax


The declaration of C++ takes the following syntax:

datatype *variable_name;
Advantages of using Pointers
Here, are pros/benefits of using Pointers

 Pointers are variables which store the address of other variables in


C++.
 More than one variable can be modified and returned by function
using pointers.
 Memory can be dynamically allocated and de-allocated using
pointers.
 Pointers help in simplifying the complexity of the program.
 The execution speed of a program improves by using pointers.

Example 1:
#include <iostream>
using namespace std;
int main() {
int x = 27;
int *ip;
ip = &x;
cout << "Value of x is : ";
cout << x << endl;
cout << "Value of ip is : ";
cout << ip<< endl;
cout << "Value of *ip is : ";
cout << *ip << endl;
return 0;
}

Pointers and Arrays


Arrays and pointers work based on a related concept. There are different
things to note when working with arrays having pointers. The array name
itself denotes the base address of the array. This means that to assign
the address of an array to a pointer, you should not use an ampersand (&).

For example:
p = arr;

The above is correct since arr represents the arrays' address. Here is
another example:

p = &arr;

The above is incorrect.

We can implicitly convert an array into a pointer. For example:

int arr [20];


int * ip;

Below is a valid operation:

ip = arr;

After the above declaration, ip and arr will be equivalent, and they will
share properties. However, a different address can be assigned to ip, but
we cannot assign anything to arr.

Example 2:

This example shows how to traverse an array using pointers:

#include <iostream>
using namespace std;
int main() {
int *ip;
int arr[] = { 10, 34, 13, 76, 5, 46 };
ip = arr;
for (int x = 0; x < 6; x++) {
cout << *ip << endl;
ip++;
}
return 0;
}
Example 3:
#include <iostream>
using namespace std;
int main() {
int *ip = NULL;
cout << "Value of ip is: " << ip;
return 0;
}

Example 4:

#include <iostream>

using namespace std;


void test(int*, int*);
int main() {
int a = 5, b = 5;
cout << "Before changing:" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

test(&a, &b);

cout << "\nAfter changing" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void test(int* n1, int* n2) {


*n1 = 10;
*n2 = 11;
}

Printing Variable Addresses in C++


#include <iostream>

using namespace std;

int main()
{

// declare variables

int var1 = 3;

int var2 = 24;

int var3 = 17;

// print address of var1

cout << "Address of var1: "<< &var1 << endl;

// print address of var2

cout << "Address of var2: " << &var2 << endl;

// print address of var3

cout << "Address of var3: " << &var3 << endl;

C++ Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms. It is a greek word. In object-oriented programming, we use 3 main
concepts: inheritance, encapsulation, and polymorphism.

Real Life Example Of Polymorphism


Let's consider a real-life example of polymorphism. A lady behaves like a teacher in
a classroom, mother or daughter in a home and customer in a market. Here, a single
person is behaving differently according to the situations.

There are two types of polymorphism in C++:


Compile time polymorphism: The overloaded functions are invoked by matching the type
and number of arguments. This information is available at the compile time and,
therefore, compiler selects the appropriate function at the compile time. It is achieved
by function overloading and operator overloading which is also known as static binding or
early binding. Now, let's consider the case where function name and prototype is same.

class A // base class declaration.


{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};

In the above case, the prototype of display() function is the same in both the base
and derived class. Therefore, the static binding cannot be applied. It would be
great if the appropriate function is selected at the run time. This is known as run
time polymorphism.

o Run time polymorphism: Run time polymorphism is achieved when the object's
method is invoked at the run time instead of compile time. It is achieved by method
overriding which is also known as dynamic binding or late binding.

Differences b/w compile time and run time


polymorphism.
Compile time polymorphism Run time polymorphism

The function to be invoked is known at the compile The function to be invoked is known at the run
time. time.

It is also known as overloading, early binding and It is also known as overriding, Dynamic binding
static binding. and late binding.

Overloading is a compile time polymorphism where Overriding is a run time polymorphism where
more than one method is having the same name but more than one method is having the same
with the different number of parameters or the name, number of parameters and the type of
type of the parameters. the parameters.

It is achieved by function overloading and operator It is achieved by virtual functions and


overloading. pointers.

It provides fast execution as it is known at the It provides slow execution as it is known at


compile time. the run time.
It is less flexible as mainly all the things execute It is more flexible as all the things execute
at the compile time. at the run time.

C++ Runtime Polymorphism Example


Let's see a simple example of run time polymorphism in C++.

// an example without the virtual keyword.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}

Output:

Eating bread...
C++ Run time Polymorphism Example: By using two
derived class
Let's see another example of run time polymorphism in C++ where we are having
two derived classes.

// an example with virtual keyword.

#include <iostream>
using namespace std;
class Shape { // base class
public:
virtual void draw(){ // virtual function
cout<<"drawing..."<<endl;
}
};
class Rectangle: public Shape // inheriting Shape class.
{
public:
void draw()
{
cout<<"drawing rectangle..."<<endl;
}
};
class Circle: public Shape // inheriting Shape class.

{
public:
void draw()
{
cout<<"drawing circle..."<<endl;
}
};
int main(void) {
Shape *s; // base class pointer.
Shape sh; // base class object.
Rectangle rec;
Circle cir;
s=&sh;
s->draw();
s=&rec;
s->draw();
s=&cir;
s->draw();
}

Output:

drawing...
drawing rectangle...
drawing circle...

Runtime Polymorphism with Data Members


Runtime Polymorphism can be achieved by data members in C++. Let's see an
example where we are accessing the field by reference variable which refers to
the instance of derived class.

#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
cout<<d.color;
}

C++ Overloading (Function and Operator)


If we create two or more members having the same name but different in number
or type of parameter, it is known as C++ overloading. In C++, we can overload:

o methods,
o constructors, and
o indexed properties

It is because these members have parameters only.

Types of overloading in C++ are:


o Function overloading
o Operator overloading

C++ Function Overloading

Function Overloading is defined as the process of having two or more function with
the same name, but different in parameters is known as function overloading in C++.
In function overloading, the function is redefined by using either different types of
arguments or a different number of arguments. It is only through these differences
compiler can differentiate between the functions.

The advantage of Function overloading is that it increases the readability of the


program because you don't need to use different names for the same action.
OOPs Concepts in Java

C++ Function Overloading Example

Let's see the simple example of function overloading where we are changing number
of arguments of add() method.

// program of function overloading when number of arguments vary.

#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

Output:

30
55

Let's see the simple example when the type of the arguments vary.

// Program of function overloading with different types of arguments.

#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);

int mul(int a,int b)


{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
std::cout << "r1 is : " <<r1<< std::endl;
std::cout <<"r2 is : " <<r2<< std::endl;
return 0;
}

Output:

r1 is : 42
r2 is : 0.6

Function Overloading and Ambiguity

When the compiler is unable to decide which function is to be invoked among the
overloaded function, this situation is known as function overloading.

When the compiler shows the ambiguity error, the compiler does not run the
program.

Causes of Function Overloading:


o Type Conversion.
o Function with default arguments.
o Function with pass by reference.

o Type Conversion:

Let's see a simple example.

#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}

The above example shows an error "call of overloaded 'fun(double)' is ambiguous".


The fun(10) will call the first function. The fun(1.2) calls the second function
according to our prediction. But, this does not refer to any function as in C++, all the
floating point constants are treated as double not as a float. If we replace float to
double, the program works. Therefore, this is a type conversion from float to double.

o Function with Default Arguments

Let's see a simple example.

#include<iostream>
using namespace std;
void fun(int);
void fun(int,int);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(int a,int b=9)
{
std::cout << "Value of a is : " <<a<< std::endl;
std::cout << "Value of b is : " <<b<< std::endl;
}
int main()
{
fun(12);

return 0;
}

The above example shows an error "call of overloaded 'fun(int)' is ambiguous". The
fun(int a, int b=9) can be called in two ways: first is by calling the function with one
argument, i.e., fun(12) and another way is calling the function with two arguments,
i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the
compiler could not be able to select among fun(int i) and fun(int a,int b=9).
o Function with pass by reference

Let's see a simple example.

#include <iostream>
using namespace std;
void fun(int);
void fun(int &);
int main()
{
int a=10;
fun(a); // error, which f()?
return 0;
}
void fun(int x)
{
std::cout << "Value of x is : " <<x<< std::endl;
}
void fun(int &b)
{
std::cout << "Value of b is : " <<b<< std::endl;
}

The above example shows an error "call of overloaded 'fun(int&)' is ambiguous".


The first function takes one integer argument and the second function takes a
reference parameter as an argument. In this case, the compiler does not know which
function is needed by the user as there is no syntactical difference between the
fun(int) and fun(int &).

C++ Operators Overloading


Operator overloading is a compile-time polymorphism in which the operator is
overloaded to provide the special meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the operators available in C++.
It is used to perform the operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined data type that is applied
to the built-in data types.

The advantage of Operators overloading is to perform different operations on the


same operand.

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Syntax of Operator Overloading


return_type class_name : : operator op(argument_list)
{
// body of the function.
}

Where the return type is the type of value returned by the function.

class_name is the name of the class.

operator op is an operator function where op is the operator being overloaded, and


the operator is the keyword.

Rules for Operator Overloading


o Existing operators can only be overloaded, but the new operators cannot be
overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void
operator ++ () operator function is defined (inside Test class).

// program to overload the unary operator ++.

#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++() {
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

Output:
The Count is: 10

Let's see a simple example of overloading the binary operators.

// program to overload the binary operators.

#include <iostream>
using namespace std;
class A
{

int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};

void A :: operator+(A a)
{

int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;

}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}

Output:

The result of the addition of two objects is : 9

C++ Function Overriding


If derived class defines same function as defined in its base class, it is known as
function overriding in C++. It is used to achieve runtime polymorphism. It enables
you to provide specific implementation of the function which is already provided by
its base class.

C++ Function Overriding Example


Let's see a simple example of Function overriding in C++. In this example, we are
overriding the eat() function.

#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{
cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}

Output:

Eating bread...

C++ Enumeration
In this article, you will learn to work with enumeration (enum). Also, you will learn where
enums are commonly used in C++ programming.

An enumeration is a user-defined data type that consists of integral constants. To define


an enumeration, keyword enum is used.

enum season { spring, summer, autumn, winter };

Here, the name of the enumeration is season.

And, spring, summer and winter are values of type season.

By default, spring is 0, summer is 1 and so on. You can change the default value of an enum
element during declaration (if necessary).

enum season

{ spring = 0,

summer = 4,

autumn = 8,

winter = 12

};

Enumerated Type Declaration

When you create an enumerated type, only blueprint for the variable is created. Here's
how you can create variables of enum type.
enum boolean { false, true };

// inside function

enum boolean check;

Here, a variable check of type enum boolean is created.

Here is another way to declare same check variable using different syntax.

enum boolean

false, true

} check;

Example 1: Enumeration Type

#include <iostream>

using namespace std;

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main()

week today;

today = Wednesday;

cout << "Day " << today+1;

return 0;

Output

Day 4
Example2: Changing Default Value of Enums

#include <iostream>

using namespace std;

enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};

int main() {

seasons s;

s = summer;

cout << "Summer = " << s << endl;

return 0;

Output

Summer = 4

Why enums are used in C++ programming?

An enum variable takes only one value out of many possible values. Example to demonstrate
it,

#include <iostream>

using namespace std;

enum suit {

club = 0,
diamonds = 10,

hearts = 20,

spades = 3

} card;

int main()

card = club;

cout << "Size of enum variable " << sizeof(card) << " bytes.";

return 0;

Output

Size of enum variable 4 bytes.

What is Exception Handling in C++?


Exception handling in C++ provides you with a way of handling unexpected circumstances
like runtime errors. So whenever an unexpected circumstance occurs, the program control
is transferred to special functions known as handlers.

To catch the exceptions, you place some section of code under exception inspection. The
section of code is placed within the try-catch block.

If an exceptional situation occurs within that section of code, an exception will be thrown.
Next, the exception handler will take over control of the program.

In case no exceptional circumstance occurs, the code will execute normally. The handlers
will be ignored.

Exception Handling Keywords


Exception handling in C++ revolves around these three keywords:

throw- when a program encounters a problem, it throws an exception. The throw keyword
helps the program perform the throw.
catch- a program uses an exception handler to catch an exception. It is added to the
section of a program where you need to handle the problem. It's done using the catch
keyword.

try- the try block identifies the code block for which certain exceptions will be activated.
It should be followed by one/more catch blocks.

Suppose a code block will raise an exception. The exception will be caught by a method
using try and catch keywords. The try/catch block should surround code that may throw an
exception. Such code is known as protected code.

Syntax:

The try/catch takes this syntax:

try {

// the protected code

} catch( Exception_Name exception1 ) {

// catch block

} catch( Exception_Name exception2 ) {

// catch block

} catch( Exception_Name exceptionN ) {

// catch block

Although we have one try statement, we can have many catch statements.

The ExceptionName is the name of the exception to be caught.

The exception1, exception2, and exceptionN are your defined names for referring to the
exceptions.

Example 1:
#include<iostream>
#include<vector>
using namespace std;

int main() {
vector<int> vec;
vec.push_back(0);
vec.push_back(1);
// access the third element, which doesn't exist
try
{
vec.at(2);
}
catch (exception& ex)
{
cout << "Exception occurred!" << endl;
}
return 0;
}

Output:

Example 2:
#include <iostream>
using namespace std;
double zeroDivision(int x, int y) {

if (y == 0) {
throw "Division by Zero!";
}
return (x / y);
}

int main() {
int a = 11;
int b = 0;
double c = 0;

try {
c = zeroDivision(a, b);
cout << c << endl;
}
catch (const char* message) {
cerr << message << endl;
}
return 0;
}
Example 3:
#include <iostream>
#include <exception>
using namespace std;

class newException : public exception


{
virtual const char* what() const throw()
{
return "new Exception occurred";
}
} newex;

int main() {

try {
throw newex;
}
catch (exception& ex) {
cout << ex.what() << '\n';
}
return 0;
}

You might also like