0% found this document useful (0 votes)
3 views81 pages

Unit I

C++ was developed by Bjarne Stroustrup in the 1980s as an extension of C to support object-oriented programming. Key features of C++ include its object-oriented nature, machine independence, simplicity, and support for dynamic memory allocation. The language has evolved through various standards, with significant updates like C++11 introducing new functionalities and libraries.

Uploaded by

radhe Chavhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views81 pages

Unit I

C++ was developed by Bjarne Stroustrup in the 1980s as an extension of C to support object-oriented programming. Key features of C++ include its object-oriented nature, machine independence, simplicity, and support for dynamic memory allocation. The language has evolved through various standards, with significant updates like C++11 introducing new functionalities and libraries.

Uploaded by

radhe Chavhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 81

UNIT-I

History of C++
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.

C++ was made available outside Bell Laboratories in 1985. The first commercial C++
compiler, Cfront, was released in 1985. It was only a front-end compiler for C. The American
National Standard Institute (ANSI) formed a committee for (precise description of computer
language) C++, in 1989. The first draft standards were published in 1995. The draft was
modified.

In 2005, the same committee of C++ discharged a technical report (called as TR1)
particularization varied options they were aiming to boost the newest C++ standard.

 In mid-2011, the new C++ customary (dubbed C++11) got finished. The Boost
library project created a substantial impact on the new rule, and a few of the new
modules were derived directly from the corresponding Boost libraries. A number of
the new options that got included were:

1. New for loop syntax providing practicality just like foreach loops in specific
different languages

2. Customary threading library (which up till 2011 each C and C++ were
lacking)

3. Variadic templates

4. Automotive vehicle (AUTO) keyword

5. New instrumentation categories & classes

6. New C++ time library, atomics support

7. Comprehensive organization library

8. Regular expression support

1
9. Higher support for unions and array-initialization lists

Features Of C++

1. Object-Oriented Programming

C++ is an Object-Oriented Programming Language, unlike C which is a procedural


programming language. This is the most important feature of C++. It can create/destroy
objects while programming. Also, It can create blueprints with which objects can be created.
We have discussed the Object-Orient Programming Concepts in C++ in this article.

Concepts of Object-oriented programming Language:

Class

Objects

Encapsulation

Polymorphism

Inheritance

2
Abstraction

2. Machine Independent

A C++ executable is not platform-independent (compiled programs on Linux won’t run on


Windows), however, they are machine-independent. Let us understand this feature of C++
with the help of an example. Suppose you have written a piece of code that can run on
Linux/Windows/Mac OSx which makes the C++ Machine Independent but the executable
file of the C++ cannot run on different operating systems.

3. Simple

It is a simple language in the sense that programs can be broken down into logical units and
parts, has rich library support and has a variety of data types. Also, the Auto Keyword of C++
makes life easier.

Auto Keyword

The idea of the auto keyword was to form the C++ compiler to deduce the data type while
compiling instead of making you declare the data type every freaking time. Do keep in mind
that you cannot declare something without an initializer. There must be some way for the
compiler to deduce your type.

4. High-Level Language

C++ is a High-Level Language, unlike C which is a Mid-Level Programming Language. It


makes life easier to work in C++ as it is a high-level language it is closely associated with the
human-comprehensible English language.

5. Popular

C++ can be the base language for many other programming languages that supports the
feature of object-oriented programming. Bjarne Stroustrup found Simula 67, the first object-
oriented language ever, lacking simulations, and decided to develop C++.

6. Case-sensitive

It is clear that C++ is a case-sensitive programming language. For example, cin is used to
take input from the input stream. But if the “Cin” won’t work. Other languages like HTML
and MySQL are not case-sensitive languages.

3
7. Compiler Based

C++ is a compiler-based language, unlike Python. That is C++ programs used to be compiled
and their executable file is used to run them. C++ is a relatively faster language than Java and
Python.

8. Dynamic Memory Allocation

When the program executes in C++ then the variables are allocated the dynamical heap
space. Inside the functions, the variables are allocated in the stack space. Many times, We are
not aware in advance how much memory is needed to store particular information in a
defined variable and the size of required memory can be determined at run time.

9. Memory Management

C++ allows us to allocate the memory of a variable or an array in run time. This is known as
Dynamic Memory Allocation.

In other programming languages such as Java and Python, the compiler automatically
manages the memories allocated to variables. But this is not the case in C++.

In C++, the memory must be de-allocated dynamically allocated memory manually after it is
of no use.

The allocation and deallocation of the memory can be done using the new and delete
operators respectively.

10.Multi-threading

Multithreading is a specialized form of multitasking and multitasking is a feature that allows


your system to execute two or more programs concurrently. In general, there are two sorts of
multitasking: process-based and thread-based.

Process-based multitasking handles the concurrent execution of programs. Thread-based


multitasking deals with the multiprogramming of pieces of an equivalent program.

A multithreaded program contains two or more parts that will run concurrently. Each part of
such a program is named a thread, and every thread defines a separate path of execution.

C++Tokens

4
Tokens in C++

Tokens in C++ are the smallest individual unit of a program.

The following tokens are available in C++ which are similar to that seen in C with the
addition of certain exclusive keywords, strings, and operators:

 Keywords
 Identifiers
 Constants
 Strings
 Special symbols
 Operators
3. C++ Keywords

Keywords in C++ refer to the pre-existing, reserved words, each holding its own position
and power and has a specific function associated with it.
It is important to note that we cannot use C++ keywords for assigning variable names as it
would suggest a totally different meaning entirely and would be incorrect.

Here is a list of keywords available in C++ according to the latest standards:

alignas alignof asm auto bool break

case catch char char16_t char32_t class

const constexpr const_cast continue decltype default

delete double do dynamic_cast else enum

explicit export extern FALSE float for

5
friend goto if inline int long

mutable namespace new noexcept nullptr operator

reinterpret_cas
private protected public register return
t

short signed sizeof static static_assert static_cast

struct switch template this thread_local throw

TRUE try typedef typeid typename union

unsigne
using virtual void volatile wchar_t
d

while – – – – –

C++ Identifiers

C++ allows the programmer to assign names of his own choice to variables, arrays, functions,
structures, classes, and various other data structures called identifiers. The programmer may
use the mixture of different types of character sets available in C++ to name an identifier.

Rules for C++ Identifiers

There are certain rules to be followed by the user while naming identifiers, otherwise, you
would get a compilation error. These rules are:

1. First character: The first character of the identifier in C++ should positively begin with
either an alphabet or an underscore. It means that it strictly cannot begin with a number.
2. No special characters: C++ does not encourage the use of special characters while
naming an identifier. It is evident that we cannot use special characters like the
exclamatory mark or the “@” symbol.
3. No keywords: Using keywords as identifiers in C++ is strictly forbidden, as they are
reserved words that hold a special meaning to the C++ compiler. If used purposely, you
would get a compilation error.
4. No white spaces: Leaving a gap between identifiers is discouraged. White spaces
incorporate blank spaces, newline, carriage return, and horizontal tab.
5. Word limit: The use of an arbitrarily long sequence of identifier names is restrained. The
name of the identifier must not exceed 31 characters, otherwise, it would be
insignificant.
6. Case sensitive: In C++, uppercase and lowercase characters connote different meanings.

6
Here is a table which illustrates the valid use of Identifiers:

Identifier Valid or Correction or alternative,


Elucidation if invalid
Name Invalid if invalid

It violates Rule 1 as it begins with


5th_element Invalid element_5
a digit

_delete Valid – –

It violates Rule 2 as it contains a


school.fee Invalid school_fee
special character ‘.’

It violates Rule 3 as it contains a


register[5] Invalid Register[5]
keyword

Student[10] Valid – –

employee It violates Rule 4 as it contains a


Invalid employee _name
name blank space

perimeter() Valid – –

C++ Constants
Before we begin our discussion on constants in C++, it is important to note that we can use
the terms “constants” and “literals” interchangeably.

As the name itself suggests, constants are referred to as fixed values that cannot change their
value during the entire program run as soon as we define them.

Syntax:
const data_type variable_name = value;
Types of Constants in C++

The different types of constants are:

 Integer constants – These constants store values of the int data type.
For instance:

const int data = 5;


 Floating constants – These constants store values of the float data type.
For instance:

const float e = 2.71;

7
 Character constants – These constants store values of the character data type.
For instance:

const char answer = ‘y’;


 String constants – These constants are also of the character data type but differ in the
declaration part.
For instance:

const char title[] = ‘‘DataFlair’’;


 Octal constants – The number system which consists of only 8 digits, from 0 to 7 is
called the octal number system. The constant octal values can be declared as:
const int oct = 034;
It is the octal equivalent of the digit 28 in the decimal number system.

 Hexadecimal constants – The number system which consists of 16 digits, from 0 to 9 and
alphabets ‘a’ to ‘f’ is called hexadecimal number system. The constant hexadecimal
values can be declared as:
const int hex = 0x40;
It is the hexadecimal equivalent of the digit 64 in the decimal number system.

C++ Strings

Just like characters, strings in C++ are used to store letters and digits. Strings can be referred
to as an array of characters as well as an individual data type.
It is enclosed within double quotes, unlike characters which are stored within single quotes.
The termination of a string in C++ is represented by the null character, that is, ‘\0’. The size
of a string is the number of individual characters it has.
In C++, a string can be declared in the following ways:

char name[30] = ‘’Hello!”; // The compiler reserves 30 bytes of memory for the string.
char name[] = “Hello!”; // The compiler reserves the required amount of memory for the
string.
char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};; // This is how a string is represented as a set of
characters.
string name = “Hello” // The compiler reserves 32 bytes of memory.

Special Symbols

Apart from letters and digits, there are some special characters in C++ which help you
manipulate or perform data operations. Each special symbol has a specific meaning to the C+
+ compiler.
Here is a table which illustrates some of the special characters in C:
Special
Trivial Name Function
Character

The opening and closing brackets of an array symbolize


[] Square brackets
single and multidimensional subscripts.

8
The opening and closing brackets represent function
() Simple brackets
declaration and calls, used in print statements.

The opening and closing curly brackets to denote the start


{} Curly braces and end of a particular fragment of code which may be
functions, loops or conditional statements

We use commas to separate more than one statements, like


, Comma
in the declaration of different variable names

Hash / Pound / The hash symbol represents a preprocessor directive used


#
Preprocessor for denoting the use of a header file

We use the asterisk symbol in various respects such as to


* Asterisk
declare pointers, used as an operand for multiplication

~ Tilde We use the tilde symbol as a destructor to free memory

. Period / dot The use the dot operator to access a member of a structure

C++ Operators

Operators are tools or symbols which are used to perform a specific operation on data.
Operations are performed on operands. Operators can be classified into three broad categories
according to the number of operands used.

Unary: It involves the use of one a single operand. For instance, ’!’ is a unary operator which
operates on a single variable, say ‘c’ as !c which denotes its negation or complement.
Binary: It involves the use of 2 operands. They are further classified as:
 Arithmetic
 Relational
 Logical
 Assignment
 Bitwise
 Conditional
Ternary: It involves the use of 3 operands. For instance, ?: is used to in place of if-else
conditions.

C++ Variables
Variables are containers for storing data values.

Declaring (Creating) Variables


To create a variable, specify the type and assign it a value:

9
Syntax
type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of the variable
(such as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;


cout << myNum;

Scope of a Variable

Scope of a variable defines the region of the code where a particular variable can be
referenced or used. Scope holds the current state of variables along with their respective
values. Scope of a variable is depends on where the value is declared in the program.
Once, a variable is declared, we can access and manipulate its data according to our needs.
Understanding how the variable's value is accessed and used within its scope is essential to
find out the program's behavior.
Once the program exits the scope where a variable is defined, the memory allocated to that
variable is usually released, making the variable inaccessible. This ensures that resources
are efficiently managed and prevents accidental access or modification of the variable's
data outside its intended scope.
Scope of a variable in C++
Similar to C, Variables in C++ can have two types of scopes:

 Local Scope or Block Scope: The variables declared within the local scope are called
local variables. Local variables are visible in the block they are declared in and other
blocks nested inside that block.
 Global Scope or File Scope: The variables declared in the global scope are called
global variables. Global variables are visible in every part of the program.
Below is the implementation of different types of Scopes in C++:
#include <iostream.h>
int global_var = 10; // Global variable

void printValues() {
int local_var = 20; // Local variable
{
int block_var = 30; // Block variable
cout << "Inside block: local_var = " << local_var << ", block_var = " << block_var <<
endl;
}
cout << "Inside function: local_var = " << local_var << endl;
}

10
int main() {
cout << "In main: global_var = " << global_var << endl;
printValues();
return 0;
}

Output

In main: global_var = 10
Inside block: local_var = 20, block_var = 30
Inside function: local_var = 20

Scope Resolution Operator


In C++, the scope resolution operator (::) is used to access the identifiers such as variable
names and function names defined inside some other scope in the current scope. Let’s take a
look at an example:

#include <iostream>

int main() {

// Accessing cout from std namespace using scope

// resolution operator

std::cout << "GeeksforGeeks";

return 0;

Output

GeeksforGeeks

11
Explanation: The std namespace contains the declaration of cout. So, to use cout, we first
need to tell the compiler that it is declared inside the std namespace which is done using ::.
The compiler then resolves the cout from there.

Syntax of Scope Resolution Operator

The scope resolution operator follows this general syntax:

scope_name :: identifier

where scope_name is the name of the scope where identifier is defined.

Applications of Scope Resolution Operator

Following are the main applications of scope resolution operator illustrated with an example:

Accessing Global Variables

When a local variable shadows a global variable, we can use :: to access the global variable.

#include <iostream.h>

using namespace std;

// Global x

int x = 3;

int main() {

// Local x

int x = 10;

// Printing the global x

cout << ::x;

return 0;

12
Output

Define Class Member Function Outside Class

It is also used to define the member function of the class outside the class template.

#include <iostream>

using namespace std;

// A sample class

class A {

public:

// Only declaration of member function

void fun();

};

// Definition outside class by referring to it

// using ::

void A::fun() {

cout << "fun() called";

int main() {

A a;

a.fun();

return 0;

13
Output

fun() called

Type Conversion in C++

Last Updated : 30 Dec, 2024

Type conversion

Type conversion means converting one type of data to another compatible type such that it
doesn’t lose its meaning. It is essential for managing different data types in C++.

Let’s take a look at an example:

#include <iostream>

using namespace std;

int main() {

// Two variables of different type

int i = 10;

char c = 'A';

// printing c after manually converting it

cout << (int)c << endl;

// Adding i and c,

int sum = i + c;

// Printing sum

cout << sum;

14
return 0;

Output

65

75

Implicit Type Conversion

Implicit type conversion (also known as coercion) is the conversion of one type of data to
another type automatically by the compiler when needed. It happens automatically when:

Operations are performed on values of different data types.

If you pass an argument to a function that expects a different data type.

Assigning a value of one data type to a variable of another data type.

Example:

#include <iostream>

using namespace std;

int main() {

int i = 10;

char c = 'a';

// c implicitly converted to int. ASCII

// value of 'a' is 97

i = i + c;

// x is implicitly converted to float

15
float f = i + 1.0;

cout << "i = " << i << endl

<< "c = " << c << endl

<< "f = " << f;

return 0;

Output

i = 107

c=a

f = 108

Explicit typecasting in c++ is done using the assignment operator is also referred to as a
forced casting. This conversion is done by explicitly declaring the required data type in front
of the expression. It can be done in two ways:

1. C-style type casting:

This type of casting is usually used in the C programming language. It is also known as cast
notation. The syntax for this casting is:

(datatype)expression;

For example:

#include <iostream>

using namespace std;

16
int main() {

char char_var = 'a';

int int_var;

// Explicitly converting a character variable to an integer variable.

int_var = (int) char_var; // Using cast notation.

cout << "The value of char_var is: " << char_var << endl;

cout << "The value of int_var is: " << int_var << endl;

return 0;

Output:

The value of char_var is: a

The value of int_var is: 97

In this example, we explicitly converted a char variable into an int. The result is the character
'a' was converted to 97.

2. Function style casting

As the name suggests, we can perform explicit typecasting using function-style notations. It
is also known as old C++-style type casting. The syntax for this casting is:

datatype(expression);

17
For example:

#include <iostream>

using namespace std;

int main() {

int int_var = 17;

float float_var;

float_var = float(int_var) / 2;

// Explicitly converting an int to a float.

cout << "The value of float_var is: " << float_var << endl;

return 0;

Output:

The value of float_var is: 8.5

In this example, we used the function style casting to convert an int variable to float. This is
why after dividing the variable by 2, we got 8.5 as the output. If we had not done that, the
output would have been 8.

Type Casting
Conversion Using the Cast Operator

18
Besides using the assignment operator, we can also use the cast operator for typecasting. The
cast operator forces the conversion of one data type to another. It is a type of unary operator.

Types of Casting in C++

There are 4 types of Casting in C++ programming language. These are:

Static Cast

Dynamic Cast

Const Cast

Reinterpret Cast

Static Cast

The Static Cast is the simplest among all four types of Casting in C++. The static cast can
perform all the conversions that are done implicitly. The typecasting using this is done at
compile time. This means that no checks are made at the run-time to ensure that the cast
performed is valid. Hence, the programmer must ensure the conversion is valid using the
static cast.

The Static cast can perform conversions between the pointers of classes related to each other.
It can perform upcast (conversion from a derived class to a base class) operations and
downcast (conversion from a base class to a derived class) operations.

The syntax for the static cast is:

static_cast <datatype> (expression)

Let us understand the static cast with an example:

#include <iostream.h>

using namespace std;

int main() {

19
double num = 3.7 * 5.5;

cout << "Before using static_cast: num = " << num << endl;

int cast_var;

cast_var = static_cast <int> (num);

cout << "After using static_cast: cast_var = " << cast_var;

return 0;

Output:

Before using static_cast: num = 20.35

After using static_cast: cast_var = 20

As we can see, after using the static_cast, double was converted to int. So, the double value
20.35 became an integer 20.

While using the static cast, we must ensure that the datatype being typecasted must be
compatible with the new data type. Otherwise, we will get an error.

Dynamic Cast

The dynamic cast can only be used with pointers and references to classes (or void*). It is a
run-time cast and is used to check the validity of a cast. The expression returns a NULL value
if the cast fails. This cast can only be used when we typecast from a parent class to a derived
class.

20
The dynamic cast uses the Run-Time Type Identification (RTTI) mechanism to make all
information about the data type of an object available at the run-time. The information is
available only for classes with at least one virtual function.

The syntax for the dynamic cast is:

dynamic_cast <datatype> (expression)

Let us understand the dynamic cast with an example:

#include <iostream.h>

using namespace std;

class Base {

public:

virtual void print() {}

};

class Derived: public Base {};

int main() {

Base* b = new Derived;

Derived* d = dynamic_cast <Derived*> (b);

if (d != NULL) {

cout << "dynamic_cast done" << endl;

} else {

cout << "dynamic_cast not done" << endl;

21
}

return 0;

Output:

dynamic_cast done

In the above example, we defined two classes - Base and Derived. The class Base contains a
virtual function, and the class Derived inherits the class Base. We created a Base class pointer
inside the main function, pointing toward a derived class object. Then, we performed
dynamic_cast on this pointer to cast it to the Derived class pointer. Because the Base class
contains a virtual function (The base class is polymorphic), the dynamic_cast is done
successfully.

Const Cast

The Const Cast is used to change an object's constant value or to remove the constant nature
of any object. Const cast is generally used in programs with one or more objects with some
constant value(s) that need to be changed at some point in the program.

For a const cast operation to be successful, the pointer and the source being cast should be of
the same data type.

The syntax for const cast is:

const_cast <datatype> (expression)

Let us understand the const cast with an example:

22
#include <iostream.h>

using namespace std;

int main() {

const int var1 = 10;

const int* ptr1 = &var1;

cout << "The old value of ptr1 is: " << *ptr1 << endl;

int* ptr2 = const_cast <int*> (ptr1);

*ptr2 = 3;

cout << "The new value of ptr1 is: " << *ptr1 << endl;

return 0;

Output:

The old value of ptr1 is: 10

The new value of ptr1 is: 3

In the above example, the constant pointer ptr1 points to the constant variable var1. We
declared another pointer, ptr2, to convert the data type const int* into int* using the
const_cast operator. Had we not used const_cast, we would have got an error. Now, because
ptr2 contains the address stored in ptr1, we could change the value of the constant pointer
ptr1 using the other pointer ptr2.

23
Reinterpret Cast

The Reinterpret Cast is used to convert one pointer type to another, regardless of whether the
classes are related. It does not check whether the pointer type and data pointed out by the
pointer are the same. That is why reinterpreting cast should not be used unless required.

Reinterpret cast is mainly used to work with bits. It does not return any value. It directly
changes the pointer type. If reinterpret cast is used on boolean values, the boolean values are
converted to integers - 0 for false and 1 for true.

The syntax for reinterpret cast is:

reinterpret_cast <datatype> (expression)

Let us understand the reinterpret cast with an example:

#include <iostream>

using namespace std;

int main() {

int* ptr = new int(98);

char* ch = reinterpret_cast <char*> (ptr);

cout << "The value of *ptr is: " << *ptr << endl;

cout << "The value of ptr is: " << ptr << endl;

cout << "The value of *ch is: " << *ch << endl;

cout << "The value of ch is: " << ch << endl;

24
return 0;

Output:

The value of *ptr is: 98

The value of ptr is: 0x562abf1cfeb0

The value of *ch is: b

The value of ch is: b

In the above example, we declared an integer pointer ptr pointing to value 98. We also
declared a character pointer ch and cast ptr to it using reinterpret cast. After printing the
values, we can observe that *ch prints 'b' as 'b' is the equivalent of 98 in ASCII. The value ch
contains 98. Hence, ch also prints the ASCII equivalent of 98, i.e., 'b'.

C++ Data Types


Data types specify the type of data that a variable can store. Whenever a variable is defined in
C++, the compiler allocates some memory for that variable based on the data type with which
it is declared as every data type requires a different amount of memory.

C++ supports a wide variety of data types, and the programmer can select the data type
appropriate to the needs of the application. For example,

#include <iostream>

using namespace std;

int main() {

// Creating a variable

int var = 10;

cout << var;

25
return 0;

Output

10

Explanation: In the above code, we needed to store the value 10 in our program, so we
created a variable var. But before var, we have used the keyword ‘int‘. This keyword is used
to define the data types of integers.

Data Types in CPP


In C++, data types are classified into the following types:

S. Type Description Data Types


No.

1 Basic Data Built-in or primitive data types that int, float, double,
Types are used to store simple values. char, bool, void

2 Derived Data array, pointer,


Data types derived from basic types.
Types reference, function

3 User Defined Custom data types created by the class, struct, union,
Data Types programmer according to their need. typedef, using

1. Character Data Type (char)

The character data type is used to store a single character. The keyword used to define a
character is char. Its size is 1 byte and it stores characters enclosed in single quotes (‘ ‘). It
can generally store upto 256 characters according to their ASCII codes.

Syntax

char name;

where name is the identifier assigned to the variable.

Example

26
#include <iostream.h>

int main() {

// Character variable

char c = 'A';

cout << c;

return 0;

Output

2. Integer Data Type (int)

Integer data type denotes that the given variable can store the integer numbers. The keyword
used to define integers is int. Its size is 4-bytes (for 64-bit) systems and can store numbers for
binary, octal, decimal and hexadecimal base systems in the range from -2,147,483,648 to
2,147,483,647.

Syntax

int name;

where, name is the identifier assigned to the variable.

Example

#include <iostream>

using namespace std;

int main() {

// Creating an integer variable

int x = 25;

27
cout << x << endl;

// Using hexadecimal base value

x = 0x15;

cout << x;

return 0;

Output

25

21

To know more about different base values in C++, refer to the article – Literals in C++

3. Boolean Data Type (bool)

The boolean data type is used to store logical values: true(1) or false(0). The keyword used to
define a boolean variable is bool. Its size is 1 byte.

Syntax

bool name;

where name is the identifier assigned to the variable.

Example

#include <iostream.h>

int main() {

// Creating a boolean variable

bool isTrue = true;

cout << isTrue;

return 0;

28
}

Output

4. Floating Point Data Type (float)

Floating-point data type is used to store numbers with decimal points. The keyword used to
define floating-point numbers is float. Its size is 4 bytes (on 64-bit systems) and can store
values in the range from 1.2E-38 to 3.4e+38.

Syntax

float name;

where, name is the identifier assigned to the variable.

#include <iostream.h>

int main() {

// Floating point variable with a decimal value

float f = 36.5;

cout << f;

return 0;

Output

36.5

5. Double Data Type (double)

The double data type is used to store decimal numbers with higher precision. The keyword
used to define double-precision floating-point numbers is double. Its size is 8 bytes (on 64-bit
systems) and can store the values in the range from 1.7e-308 to 1.7e+308

Syntax

double name;

29
where, name is the identifier assigned to the variable.

Example

#include <iostream>

using namespace std;

int main() {

// double precision floating point variable

double pi = 3.1415926535;

cout << pi;

return 0;

Output

3.14159

6. Void Data Type (void)

The void data type represents the absence of value. We cannot create a variable of void type.
It is used for pointer and functions that do not return any value using the keyword void.

Syntax

void functionName();

Example

#include <iostream>

using namespace std;

// Function with void return type

void hello() {

30
cout << "Hello, World!" << endl;

int main() {

hello();

return 0;

Output

Hello, World!

Derived Data Types in C++

The data types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. They are generally the data types that are created from the primitive
data types and provide some additional functionality.

In C++, there are four different derived data types:

Table of Content

Functions

Arrays

Pointers

References

Let’s understand each of the following derived datatypes:

Functions

A function is a block of code or program segment that is defined to perform a specific well-
defined task. It is generally defined to save the user from writing the same lines of code again
and again for the same input. All the lines of code are put together inside a single function
and this can be called anywhere required.

Let’s take a look at example that demonstrates the use of function in C++:

#include <iostream>

using namespace std;

31
// max here is a function which is a derived type

int max(int x, int y) {

if (x > y)

return x;

else

return y;

// main function is also a derived type

int main() {

int a = 10, b = 20;

// Calling above function to

// find max of 'a' and 'b'

int m = max(a, b);

cout << "m is " << m;

return 0;

Output

m is 20

Explanation: This above program demonstrates the use of function derived types It defines a
function called max this function returns the maximum of two integers provided as input. In
the main function, max function is called to find the maximum of variables a and b and store
it in m and finally print m(max number).

Arrays

32
An-array is a collection of items stored at continuous memory locations. The idea of array is
to represent many variables using a single name. The below example demonstrates the use of
array in C++.

#include <iostream>

using namespace std;

int main() {

// Array Derived Type

int arr[5] = {1, 2, 3, 4, 5};

arr[0] = 5;

arr[2] = -10;

arr[3] = arr[0];

// Printing the data

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

printf("%d ", arr[i]);

return 0;

Output

5 2 -10 5 5

Explanation: This above program shows the use of array-derived type. It creates an integer
array arr and assigns values using indices. Then it prints all the array elements.

Pointers

Pointers are symbolic representation of addresses. They can be said as the variables that can
store the address of another variable as its value. The below example demonstrates the use of
pointer in C++.

33
#include <iostream>

using namespace std;

int main() {

int var = 20;

// Pointers Derived Type

// declare pointer variable

int* ptr;

// note that data type of ptr

// and var must be same

ptr = &var;

// assign the address of a variable

// to a pointer

cout << "Value at ptr = " << ptr << endl;

cout << "Value at var = " << var << endl;

cout << "Value at *ptr = " << *ptr;

return 0;

Output

Value at ptr = 0x7fffa5bef2cc

Value at var = 20

Value at *ptr = 20

34
Explanation: This above program demonstrates the use of pointers as a derived type. It
declares pointer variable ptr and assigning the address of a variable var to it. It then prints the
values of the pointer, the variable, and the dereferenced pointer, showcasing the basics of
pointer usage in C++.

References

When a variable is declared as reference, it becomes an alternative name for an existing


variable. A variable can be declared as reference by putting ‘&’ in the declaration.

The below example demonstrates the use of reference in C++.

#include <iostream>

using namespace std;

int main() {

int x = 10;

// Reference Derived Type

// ref is a reference to x.

int& ref = x;

// Value of x is now changed to 20

ref = 20;

cout << "x = " << x << endl;

// Value of x is now changed to 30

x = 30;

cout << "ref = " << ref << endl;

return 0;

35
Output

x = 20

ref = 30

Explanation: The above program demonstrates the use of reference-derived type. A


reference ref to an integer variable x. is created. If the value of ref is changed the value x, is
also modified and vice versa.

User Defined Data Types in C++

User defined data types are those data types that are defined by the user himself. In C++,
these data types allow programmers to extend the basic data types provided and create new
types that are more suited to their specific needs. C++ supports 5 user-defined data types:

Table of Content

Class

Structure

Union

Enumeration

Typedef

1. Class

A Class is the building block of C++’s Object-Oriented programming paradigm. It is a user-


defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is like a blueprint for an
object.

Example

#include <bits/stdc++.h>

using namespace std;

class GfG {

// Access specifier

public:

36
// Data Member

string name;

// Member Function

void printname() {

cout << name;

};

int main() {

// Declare an object of class geeks

GfG g;

// Accessing data member

g.name = "GeeksForGeeks";

// Accessing member function

g.printname();

return 0;

Output

GeeksForGeeks

Explanation: The above program defines a class named GfG with a name attribute and a
function printname() to print the name. In the main function, it creates an object named g,
sets the geekname as “GeeksforGeeks“, and calls the printname() function to display it.

37
2. Structure

A Structure is a user-defined data type like class. A structure creates a data type that can be
used to group items of possibly different types into a single type.

Example

#include <iostream>

using namespace std;

// Declaring structure

struct A {

int i;

char c;

};

int main() {

// Create an instance of structure

A a;

// Initialize structure members

a.i = 65;

a.c = 'A';

cout << a.c << ": " << a.i;

return 0;

38
Output

A: 65

Explanation: The above demonstrates program demonstrates the use of structures by defining
a structure named A having i and c members. It then creates an instance if structure in the
main function, sets the members’ values, and prints them.

Structures in C++ are different from structures in C and resembles classes. Refer to this
article to learn more – Difference Between C Structures and C++ Structures

3. Union

Like structures , union is also user-defined data type used to group data of different type into
a single type. But in union, all members share the same memory location.

Example

#include <iostream>

using namespace std;

// Declaration of union is same as the structures

union A {

int i;

char c;

};

int main() {

// A union variable t

A a;

// Assigning value to c, i will also

// assigned the same

a.c = 'A';

cout << "a.i: " << a.i << endl;

39
cout << "a.c: " << a.c;

return 0;

Output

a.i: 65

a.c: A

Explanation: The above program demonstrates the use of unions. Union named A with
members i and c is defined that shares the same memory space. It is shown that when we only
assign c some value, the i also stores the same value.

4. Enumeration

Enumeration (or enum) is a user-defined data type in C++ mainly used to assign names to
integral constants, the names make a program easy to read and maintain.

Example

#include <iostream>

using namespace std;

// Declaring enum

enum Week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };

int main() {

// Creating enum variable

enum Week day;

// Assigning value to the variabe

day = Wed;

40
cout << day;

return 0;

Output

Structure of C++ Program


The structure of C++ program can have following sections.

Documentation Sections

Include file section

Class declaration section

Member function section

Main function section

1. Documentation: In this section we write comment about program that ignore by

compiler. In comments we can write program name, uses, developer name, date,

any help etc. Comments are written in /*--------*/(multiline comment) and //------

(single line comment).

// Documentation

/* Program to demonstrate POP organization and Top to

Down approach, Created by: www.LRsir.net */

2. Include file section: In this section all needful files are included in the program

that contains declaration of class and functions used in the program.

Ex: #include<iostream.h>

Contain declaration of cout and cin stream object.

3. Class declaration section: In this section we create classes. Every class contains

41
data and function declaration. In class we can also define member functions.

Ex:

class A

int a,b;

public:

void getdata(int);

void showdata();

int sum();

};

4. Member function definition: In this section, all explicit member functions of the

class are defined outside the class using scope resolution operator (::).

Ex:

void A::getdata(int p1,int p2)

a=p1;

b=p2;

void A::showdata()

cout<<"\n"<<a<<"\t"<<b;

int A::sum()

return a+b;

5. Main function section: In this section we can declare object of class and call

42
public member functions of the class.

Ex:

void main()

A ob;

ob.getdata(10);

ob.showdata();

int c=ob.sum();

cout<<"\nSum="<<c;

For example

// Documentation

/* Program to demonstrate OOPs organization and

Bottom-Up approach, Created by: www.LRsir.net

*/

//include files

#include<iostream.h>

//class declaration

class A

int a,b;

public:

void getdata(int);

void showdata();

int sum();

};

//Member function definition

43
void A::getdata(int p1,int p2)

a=p1;

b=p2;

void A::showdata()

cout<<"\n"<<a<<"\t"<<b;

int A::sum()

return a+b;

//Main function

void main()

A ob;

ob.getdata(10);

ob.showdata();

int c=ob.sum();

cout<<"\nSum="<<c;

Output:

a=10 b=20

Sum=30

I/O Statements

44
In C++, input and output are performed in the form of a sequence of bytes or more commonly
known as streams.

Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard)
to the main memory then this process is called input.

Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device (display screen) then this process is called output.

All of these streams are defined inside the <iostream> header file which contains all the
standard input and output tools of C++. The two instances cout and cin of iostream class are
used very often for printing outputs and taking inputs respectively. These two are the most
basic methods of taking input and printing output in C++.

Standard Output Stream – cout

The C++ cout is the instance of the ostream class used to produce output on the standard
output device which is usually the display screen. The data needed to be displayed on the
screen is inserted in the standard output stream (cout) using the insertion operator(<<).

Syntax

cout << value/variable;

For example, if we want to print text “GeeksforGeeks” on the display, we can use the cout as
shown:

#include <iostream>

using namespace std;

int main() {

// Printing the given text using cout

cout << "GeeksforGeeks";

return 0;

Output

GeeksforGeeks

45
Explanation: In the above program, cout is used to output the text “GeeksforGeeks” to the
standard output stream. It works in conjunction with the insertion operator (<<) to send the
specified data to the output stream.

We can also print the variable values using cout.

#include <iostream>

using namespace std;

int main() {

int a = 22;

// Printing variable 'a' using cout

cout << a;

return 0;

Output

22

Understanding input and output operations is essential for any C++ programmer. The C++
Course includes comprehensive lessons on basic I/O operations, ensuring you can manage
user interaction in your programs.

Standard Input Stream – cin

The C++ cin statement is the instance of the class istream and is used to read input from the
standard input device which is usually a keyboard. The extraction operator (>>) is used along
with the object cin for extracting the data from the input stream and store it in some variable
in the program.

Syntax

cin >> variable;

For example, if we want to ask user for his/her age, then we can use cin as shown:

#include <iostream>

using namespace std;

46
int main() {

int age;

// Output a label

cout << "Enter your age:";

// Taking input from user and store

// it in variable

cin >> age;

// Output the entered age

cout << "Age entered: " << age;

return 0;

Input

Enter your age: 18 (18 entered by the user)

Output

Your age is: 18

Explanation: The above program asks the user to input the age. The object cin is connected to
the input device (keyboard). The age entered by the user is extracted from cin using
the extraction operator(>>) and the extracted data is then stored in the variable age present on
the right side of the extraction operator.

Control Structures:
There are three types of control structures:

1. Sequence

2. Selection also called as decision making statements

47
3. Iteration

Decision making statements:

C++ language supports the decision making-statements as listed below.

The if statement

The if-else statement

The nested if-else statements.

The else-if ladder

The switch case statement.

The break statement

The default keyword

The decision-making statement checks the given condition and then executes its subblock.
The decision statement decides the statement to be executed after the success or failure of

a given condition.

The if Statement: C++ uses the keyword if to execute a set of command lines or a command

line when the logical condition is true. It has only one option. The syntax for the simplest if

statement is as shown in figure.

48
/* Write a program to declare the price of the book with if statement and check its price.

If its price is less than or equal to 600, print the output with some comment, else

terminate.*/

#include<iostream>

using namespace std;

int main()

int price;

cout<<“\nEnter the price of the book:”;

cin>>price;

if(price<=600)

cout<<“\n Hurry up buy the book!!!!!”;

49
return 0;

Output:

Enter the price of the book: 345

Hurry up buy the book!!!!!

Multiple Ifs: The syntax of multiple ifs is shown in figure. Programs on multiple ifs are as

follows.

Syntax for the multiple ifs:

if (expression) /* no semi-colon */

Statement 1;

if (expression) /* no semi-colon */

Statement 2;

if (expression) /* no semi-colon */

Statement 3;

/* Write a program to enter the percentage of marks obtained by a student and display the

class obtained.*/

#include<iostream>

using namespace std;

int main()

float per;

cout<<“\nEnter the percentage:”;

cin>>per;

if(per>=90 && per<=100)

cout<<“\nDistinction”;

if(per>=70 && per<90)

cout<<“\nFirst class”;

50
if(per>=50 && per<70)

cout<<“\nSecond class”;

if(per>=40 && per<50)

cout<<“\nPass”;

if(per<40)

cout<<“\nFail”;

return 0;

Output:

Enter the percentage: 95

Distinction.

The if-else Statement: In the if–else statement, if the expression/condition is true, the body of

the if statement is executed; otherwise, the body of the else statement is executed.

/*Write a program to enter age and display a message whether the user is eligible for

voting or not. Use if-else statement.*/

#include<iostream>

using namespace std;

int main()

51
int age;

cout<<“Enter Your Age:”;

cin>>age;

if (age>=18)

cout<<“You are eligible for voting.”;

else

cout<<“You are not eligible for voting”<<endl;

cout<< “Wait for”<<18-age<<“year(s).”;

return 0;

Output:

Enter Your Age: 17

You are not eligible for voting

Wait for 1 year(s).

Nested if-else Statements: In this kind of statement, a number of logical conditions are tested

for taking decisions. Here, the if keyword followed by an expression is evaluated. If it is true,

the compiler executes the block following the if condition; otherwise, it skips this block and

executes the else block. It uses the if statement nested inside an if-else statement, which is

nested inside another if-else statement. This kind of nesting can be limitless.

52
/* Program to print the largest of three numbers. */

#include<iostream>

using namespace std;

int main()

int a,b,c;

cout<<“\nEnter three numbers:”;

cin>>a>>b>>c;

if(a>b)

if(a>c)

cout<<“\n a is largest ”;

else

cout<<“\n c is largest ”;

else

53
{

if(b>c)

cout<<“\n b is largest ”;

else

cout<<“\n c is largest ”;

return 0;

Output:

Enter three numbers: 3 6 89

c is largest.

The else-if Ladder: A common programming construct is the else-if ladder, sometimes called

the if-else-if staircase because of its appearance. In the program one can write a ladder of elseif. The
program goes down the ladder of else-if, in anticipation of one of the expressions being

true.

/*Syntax of else-if statement can be given as follows.*/

if(condition)

statement 1; /* if block*/

statement 2;

else if(condition)

statement 3; /* else if block*/

statement 4;

else

statement 5; /* last else block */

54
statement 6;

/*Write a program to calculate energy bill. Read the starting and ending meter reading.

The charges are as follows.

No. of units Consumed Rates in (Rs.)

200 - 500 3.5

100 - 200 2.50

Less than 100 1.50 */

#include<iostream.h>

using namespace std;

int main()

int previous,current,consumed;

float total;

clrscr();

cout<<“\nInitial & Final Readings:”;

cin>>previous>>current;

consumed = current-previous;

if(consumed>=200 && consumed<=500)

total=consumed *3.50;

else if(consumed>=100 && consumed<=199)

total=consumed *2.50;

else if(consumed<100)

total=consumed*1.50;

cout<<“\n Total no of units consumed: ”<<consumed;

cout<<“\n Electric Bill for units ”<< consumed<< “is” <<total;

return 0;

55
6

Output:

Initial & final readings: 100 235

Total no of units consumed: 135

Electric bill for units 135 is 337.5

Unconditional Control Transfer Statements

The goto statement: This statement does not require any condition. This statement passes

control anywhere in the program without considering any condition. The general format for this

statement is shown in figure.

Here, a label is any valid label either before or after goto. The ‘label’ must start with any

character and can be constructed with rules used for forming identifiers. Avoid using the goto

statement.

Syntax:

goto label;

-----

-----

-----

label:

/*Write a program to demonstrate the use of goto statement.*/

##include<iostream>

using namespace std;

void main()

int x;

cout<<“Enter a Number:”;

cin>>x;

if (x%2==0) goto

even;

56
else

goto odd;

even:

cout<<x<<“ is an Even Number.”;

return;

odd:

cout<<x<<“ is an Odd Number.”;

The break Statement: The break statement allows the programmer to terminate the loop. The

break skips from the loop or the block in which it is defined.

The continue Statement

The continue statement works somewhat like the break statement. Instead of forcing the control

to the end of the loop (as it is in case of break), the continue case causes the control to pass on to

the beginning of the block/loop. In the case of for loop, the continue case initiates the testing

condition and increment on steps has to be executed (while rest of the statement following the

continue are neglected). For while and do-while, the continue case causes control to pass on to

conditional tests. It is useful in a programming situation where it is required that particular

iterations occur only up to some extent or when some part of the code has to be neglected. The

programs on continue are explained in the control loop chapter.

Switch Statements

Switch statements are like if-else statements only, but the difference here is that they check for
specific individual cases, unlike if-else statements, which also check for logical expressions.

Syntax:

switch(expression)

case value1:

57
// statements to run

break;

case value2:

// statements to run

break;

..

..

..

default:

// statements to run

Example:

#include <iostream>

using namespace std;

int main() {

int num; // Declaring num variable.

cout << "Enter a number : ";

cin >> num; // Taking the user input.

// Switch expression starts.

switch (num) {

// Checking for individual cases.

case 1:

cout << "The number is 1" << endl;

58
break;

case 2:

cout << "The number is 2" << endl;

break;

case 5:

cout << "The number is 5" << endl;

break;

default:

cout << "The number is neither 1 nor 2 nor 5" << endl;

return 0;

Input:

Output:

The number is 2

Iteration Statements

As discussed above, sometimes, in our program, when we want to repeat a certain set of
instructions, we can wrap them inside a loop. In C++, we have three types of iteration or loop
statements:

While loop

59
Do while loop

For loop

while loop While loop is used when we want to run a loop till a condition is evaluated to be
true

Syntax:

while [condition of loop] {

// statements to run

Example:

#include <iostream>

using namespace std;

int main() {

int end; // Declaring the end variable.

cout << "Enter the number till which you want to print : ";

cin >> end; // Taking the user input.

int start = 1; // Initialzing the start.

// Loop start

while (start <= end) // Termination condition

60
// Statements.

cout << start << endl;

// Incrementing the start variable, so that at some point loop condition

// becomes false, and the program exits the loop.

start++;

return 0;

Input:

10

Output:

..

..

10

do-while loop This is the same as the while loop. The only difference is that the loop runs at
least once, whether the condition is true or false.

Syntax:

61
do {

// Statements to run.

} while (condition to be checked);

Example:

#include <iostream>

using namespace std;

int main() {

int end; // Declaring the end variable.

cout << "Enter the number till which you want to print : ";

cin >> end; // Taking the user input.

int start = 12; // Initialzing the start.

// Loop termination condition.

do {

// Statements

cout << start << endl;

// incrementing the start variable, so that at some point loop condition

// becomes false, and the program exits the loop

start++;

} while (start <= end);

62
// Even if the condition is false, still,

// the loop will run once and will print 12.

return 0;

Input

10

Output:

12

for loop is used when we are exactly sure in numbers for how many times our loop has to
run.

Syntax:

for(initialization; termination; increment or decrement) {

// Statements to run.

Example:

#include <iostream>

63
using namespace std;

int main() {

int end; // Declaring the end variable.

cout << "Enter the number till which you want to print : ";

cin >> end; // Taking the user input.

// Loop start.

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

cout << i << endl;

return 0;

Output:

Enter the number till which you want to print : 10

64
9

10

Here we have just taken a small glimpse of what Iteration Statements in C++ are.

To understand deeply about loops, visit here

Jump Statements

As the name suggests, jump statements are used to jump out of a block of code, be it a
conditional statement, an iteration statement, or something else.

In C++, we generally have 4 types of jump statements:

break

continue

goto

exit()

break statements Moves the program flow out of the current block when encountered.

Example:

#include <iostream.h>

using namespace std;

int main() {

// Loop statement start.

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

// If the condition is met.

65
if (i == 5) {

// When a break statement is encountered, the program will exit the loop.

break;

cout << i << endl; // Printing the i's value.

return 0;

Output:

The point to remember is that it only exits the first block or block in scope, i.e., if we are in
nested blocks, which means, block inside a block, then it will only exit the most inner block.

continue statement When encountered, it just skips that particular iteration, which means we
are telling the compiler that as soon as you see the continue statement, forget everything
written below it for that iteration, and start with the next iteration.

Example:

66
#include <iostream.h>

using namespace std;

int main() {

// Loop statement start.

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

// If the condition is met.

if (i == 5) {

// When continue statement will be encountered,

// the program will skip that iteration.

continue;

cout << i << endl; // Printing the i's value.

return 0;

Output:

67
4

the goto statement is used to move the program flow to a user-defined label. The use of goto
is discouraged, as it sometimes confuses fellow programmers and those who will read our
code.

Example:

#include <iostream>

using namespace std;

int main() {

int num = 0; // Initializing num variable.

start: // Defining the label.

cout << num << endl;

num++; // Incrementing num variable.

// Checking condition.

if (num < 10) {

// If true, execute the goto statement, and move to label "start".

goto start;

68
cout << "End Reached"; // Finally printing

return 0;

Output:

End Reached

We can see that goto can be used as a loop, along with a jump statement, but it is advised to
avoid the use of goto statements.

exit() function The purpose of using exit() is to terminate or exit the current program with a
specific exit code.

Example:

#include <iostream.h>

int main() {

69
for (int i = 0; i < 10; i++) {

if (i == 5) {

exit(0);

cout << i << endl;

return 0;

Output:

It will exit the program, and the value we have supplied to the exit() function, here 0, will be
returned to the operating system as the program's exit code.

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

70
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;

Operator Operation Here, the + operator is used


to add two variables a and
+ Addition b. Similarly there are
various other arithmetic
- Subtraction operators in C++.

* Multiplication
Example 1: Arithmetic
/ Division Operators

#include <iostream>
% Modulo Operation (Remainder after division)
using namespace std;

int main() {

int a, b;

a = 7;

b = 2;

// printing the sum of a and b

cout << "a + b = " << (a + b) << endl;

71
// printing the difference of a and b

cout << "a - b = " << (a - b) << endl;

// printing the product of a and b

cout << "a * b = " << (a * b) << endl;

// printing the division of a by b

cout << "a / b = " << (a / b) << endl;

// printing the modulo of a by b

cout << "a % b = " << (a % b) << endl;

return 0;

Run Code

Output

a+b=9

a-b=5

a * b = 14

a/b=3

a%b=1

Here, the operators +, - and * compute addition, subtraction, and multiplication respectively
as we might have expected.

C++ Assignment Operators

72
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;

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;

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

Example 3: Assignment Operators

#include <iostream>

using namespace std;

int main() {

int a, b;

// 2 is assigned to a

a = 2;

// 7 is assigned to b

b = 7;

cout << "a = " << a << endl;

cout << "b = " << b << endl;

cout << "\nAfter a += b;" << endl;

// assigning the sum of a and b to a

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

cout << "a = " << a << endl;

return 0;

Run Code

Output

74
a=2

b=7

After a += b;

a=9

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


>= 3 >= 5 give us false
To

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

Example 4: Relational Operators

#include <iostream>

75
using namespace std;

int main() {

int a, b;

a = 3;

b = 5;

bool result;

result = (a == b); // false

cout << "3 == 5 is " << result << endl;

result = (a != b); // true

cout << "3 != 5 is " << result << endl;

result = a > b; // false

cout << "3 > 5 is " << result << endl;

result = a < b; // true

cout << "3 < 5 is " << result << endl;

result = a >= b; // false

cout << "3 >= 5 is " << result << endl;

result = a <= b; // true

cout << "3 <= 5 is " << result << endl;

return 0;

76
}

Run Code

Output

3 == 5 is 0

3 != 5 is 1

3 > 5 is 0

3 < 5 is 1

3 >= 5 is 0

3 <= 5 is 1

Note: Relational operators are used in decision-making and loops.

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

Logical AND.
expression1 &&
&& True only if all the operands are
expression2
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.

In C++, logical operators are commonly used in decision making. To further understand the
logical operators, let's see the following examples,

77
Suppose,

a=5

b=8

Then,

(a > 3) && (b > 5) evaluates to true

(a > 3) && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true

(a > 3) || (b < 5) evaluates to true

(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true

!(a > 3) evaluates to false

Example 5: Logical Operators

#include <iostream>

using namespace std;

int main() {

bool result;

result = (3 != 5) && (3 < 5); // true

cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5); // false

78
cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5); // false

cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5); // true

cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5); // true

cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5); // false

cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2); // true

cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5); // false

cout << "!(5 == 5) is " << result << endl;

return 0;

Output

(3 != 5) && (3 < 5) is 1

(3 == 5) && (3 < 5) is 0

(3 == 5) && (3 > 5) is 0

(3 != 5) || (3 < 5) is 1

79
(3 != 5) || (3 > 5) is 1

(3 == 5) || (3 > 5) is 0

!(5 == 2) is 1

!(5 == 5) is 0

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

Other C++ Operators

Here's a list of some other common operators available in C++.

Operator Description Example

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

returns value based on the string result = (5 > 0) ? "even"


?:
condition : "odd"; // "even"

represents memory address of the


& &num; // address of num
operand

80
accesses members of struct
. s1.marks = 92;
variables or class objects

used with pointers to access the


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

<< prints the output value cout << 5;

>> gets the input value cin >> num;

81

You might also like