Unit I
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.
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
1
9. Higher support for unions and array-initialization lists
Features Of C++
1. Object-Oriented Programming
Class
Objects
Encapsulation
Polymorphism
Inheritance
2
Abstraction
2. Machine Independent
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
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.
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
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++
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.
5
friend goto if inline int long
reinterpret_cas
private protected public register return
t
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.
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:
_delete Valid – –
Student[10] Valid – –
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++
Integer constants – These constants store values of the int data type.
For instance:
7
Character constants – These constants store values of the character data type.
For instance:
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
8
The opening and closing brackets represent function
() Simple brackets
declaration and calls, used in print statements.
. 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.
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:
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
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() {
// resolution operator
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.
scope_name :: identifier
Following are the main applications of scope resolution operator illustrated with an example:
When a local variable shadows a global variable, we can use :: to access the global variable.
#include <iostream.h>
// Global x
int x = 3;
int main() {
// Local x
int x = 10;
return 0;
12
Output
It is also used to define the member function of the class outside the class template.
#include <iostream>
// A sample class
class A {
public:
void fun();
};
// using ::
void A::fun() {
int main() {
A a;
a.fun();
return 0;
13
Output
fun() called
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++.
#include <iostream>
int main() {
int i = 10;
char c = 'A';
// Adding i and c,
int sum = i + c;
// Printing sum
14
return 0;
Output
65
75
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:
If you pass an argument to a function that expects a different data type.
Example:
#include <iostream>
int main() {
int i = 10;
char c = 'a';
// value of 'a' is 97
i = i + c;
15
float f = i + 1.0;
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:
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>
16
int main() {
int int_var;
cout << "The value of char_var is: " << char_var << endl;
cout << "The value of int_var is: " << int_var << endl;
return 0;
Output:
In this example, we explicitly converted a char variable into an int. The result is the character
'a' was converted to 97.
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>
int main() {
float float_var;
float_var = float(int_var) / 2;
cout << "The value of float_var is: " << float_var << endl;
return 0;
Output:
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.
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.
#include <iostream.h>
int main() {
19
double num = 3.7 * 5.5;
cout << "Before using static_cast: num = " << num << endl;
int cast_var;
return 0;
Output:
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.
#include <iostream.h>
class Base {
public:
};
int main() {
if (d != NULL) {
} else {
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.
22
#include <iostream.h>
int main() {
cout << "The old value of ptr1 is: " << *ptr1 << endl;
*ptr2 = 3;
cout << "The new value of ptr1 is: " << *ptr1 << endl;
return 0;
Output:
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.
#include <iostream>
int main() {
cout << "The value of *ptr is: " << *ptr << endl;
cout << "The value of ptr is: " << ptr << endl;
cout << "The value of *ch is: " << *ch << endl;
24
return 0;
Output:
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++ 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>
int main() {
// Creating a variable
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.
1 Basic Data Built-in or primitive data types that int, float, double,
Types are used to store simple values. char, bool, void
3 User Defined Custom data types created by the class, struct, union,
Data Types programmer according to their need. typedef, using
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;
Example
26
#include <iostream.h>
int main() {
// Character variable
char c = 'A';
cout << c;
return 0;
Output
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;
Example
#include <iostream>
int main() {
int x = 25;
27
cout << x << endl;
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++
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;
Example
#include <iostream.h>
int main() {
return 0;
28
}
Output
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;
#include <iostream.h>
int main() {
float f = 36.5;
cout << f;
return 0;
Output
36.5
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>
int main() {
double pi = 3.1415926535;
return 0;
Output
3.14159
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>
void hello() {
30
cout << "Hello, World!" << endl;
int main() {
hello();
return 0;
Output
Hello, World!
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.
Table of Content
Functions
Arrays
Pointers
References
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>
31
// max here is a function which is a derived type
if (x > y)
return x;
else
return y;
int main() {
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>
int main() {
arr[0] = 5;
arr[2] = -10;
arr[3] = arr[0];
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>
int main() {
int* ptr;
ptr = &var;
// to a pointer
return 0;
Output
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
#include <iostream>
int main() {
int x = 10;
// ref is a reference to x.
int& ref = x;
ref = 20;
x = 30;
return 0;
35
Output
x = 20
ref = 30
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
Example
#include <bits/stdc++.h>
class GfG {
// Access specifier
public:
36
// Data Member
string name;
// Member Function
void printname() {
};
int main() {
GfG g;
g.name = "GeeksForGeeks";
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>
// Declaring structure
struct A {
int i;
char c;
};
int main() {
A a;
a.i = 65;
a.c = 'A';
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>
union A {
int i;
char c;
};
int main() {
// A union variable t
A a;
a.c = 'A';
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>
// Declaring enum
int main() {
day = Wed;
40
cout << day;
return 0;
Output
Documentation Sections
compiler. In comments we can write program name, uses, developer name, date,
any help etc. Comments are written in /*--------*/(multiline comment) and //------
// Documentation
2. Include file section: In this section all needful files are included in the program
Ex: #include<iostream.h>
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:
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
*/
//include files
#include<iostream.h>
//class declaration
class A
int a,b;
public:
void getdata(int);
void showdata();
int sum();
};
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++.
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
For example, if we want to print text “GeeksforGeeks” on the display, we can use the cout as
shown:
#include <iostream>
int main() {
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.
#include <iostream>
int main() {
int a = 22;
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.
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
For example, if we want to ask user for his/her age, then we can use cin as shown:
#include <iostream>
46
int main() {
int age;
// Output a label
// it in variable
return 0;
Input
Output
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
47
3. Iteration
The if statement
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
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>
int main()
int price;
cin>>price;
if(price<=600)
49
return 0;
Output:
Multiple Ifs: The syntax of multiple ifs is shown in figure. Programs on multiple ifs are as
follows.
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>
int main()
float per;
cin>>per;
cout<<“\nDistinction”;
cout<<“\nFirst class”;
50
if(per>=50 && per<70)
cout<<“\nSecond class”;
cout<<“\nPass”;
if(per<40)
cout<<“\nFail”;
return 0;
Output:
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
#include<iostream>
int main()
51
int age;
cin>>age;
if (age>=18)
else
return 0;
Output:
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>
int main()
int a,b,c;
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:
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.
if(condition)
statement 1; /* if block*/
statement 2;
else if(condition)
statement 4;
else
54
statement 6;
/*Write a program to calculate energy bill. Read the starting and ending meter reading.
#include<iostream.h>
int main()
int previous,current,consumed;
float total;
clrscr();
cin>>previous>>current;
consumed = current-previous;
total=consumed *3.50;
total=consumed *2.50;
else if(consumed<100)
total=consumed*1.50;
return 0;
55
6
Output:
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
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:
##include<iostream>
void main()
int x;
cout<<“Enter a Number:”;
cin>>x;
if (x%2==0) goto
even;
56
else
goto odd;
even:
return;
odd:
The break Statement: The break statement allows the programmer to terminate the loop. The
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
iterations occur only up to some extent or when some part of the code has to be neglected. The
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>
int main() {
switch (num) {
case 1:
58
break;
case 2:
break;
case 5:
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:
// statements to run
Example:
#include <iostream>
int main() {
cout << "Enter the number till which you want to print : ";
// Loop start
60
// Statements.
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.
Example:
#include <iostream>
int main() {
cout << "Enter the number till which you want to print : ";
do {
// Statements
start++;
62
// Even if the condition is false, still,
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:
// Statements to run.
Example:
#include <iostream>
63
using namespace std;
int main() {
cout << "Enter the number till which you want to print : ";
// Loop start.
return 0;
Output:
64
9
10
Here we have just taken a small glimpse of what Iteration Statements in C++ are.
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.
break
continue
goto
exit()
break statements Moves the program flow out of the current block when encountered.
Example:
#include <iostream.h>
int main() {
65
if (i == 5) {
// When a break statement is encountered, the program will exit the loop.
break;
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>
int main() {
if (i == 5) {
continue;
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>
int main() {
// Checking condition.
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);
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.
Arithmetic Operators
Assignment Operators
70
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,
a + b;
* 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;
71
// printing the difference of a and b
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.
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;
= 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;
#include <iostream>
int main() {
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
a += b; // a = a +b
return 0;
Run Code
Output
74
a=2
b=7
After a += b;
a=9
A relational operator is used to check the relationship between two operands. For example,
a > b;
#include <iostream>
75
using namespace std;
int main() {
int a, b;
a = 3;
b = 5;
bool result;
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
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.
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,
#include <iostream>
int main() {
bool result;
cout << "(3 != 5) && (3 < 5) is " << result << endl;
78
cout << "(3 == 5) && (3 < 5) is " << result << endl;
cout << "(3 == 5) && (3 > 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
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 OR
^ Binary XOR
80
accesses members of struct
. s1.marks = 92;
variables or class objects
81