0% found this document useful (0 votes)
20 views92 pages

Unit1 OOPs

The document provides study material on Object-Oriented Programming (OOP) with C++, covering key concepts such as classes, objects, encapsulation, abstraction, inheritance, polymorphism, and dynamic binding. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting the benefits of OOP like reusability, data hiding, and reduced complexity. Additionally, it outlines differences between C and C++, including their respective programming paradigms and features.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views92 pages

Unit1 OOPs

The document provides study material on Object-Oriented Programming (OOP) with C++, covering key concepts such as classes, objects, encapsulation, abstraction, inheritance, polymorphism, and dynamic binding. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting the benefits of OOP like reusability, data hiding, and reduced complexity. Additionally, it outlines differences between C and C++, including their respective programming paradigms and features.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 92

OOPs With C++

IQBAL INSTITUTE OF TECHNOLOGY AND MANAGEMENT


Laloo Sheshgaribagh Hyderpora Srinagar – 190014

OOPs WITH C++


STUDY MATERIAL
For
BCA – 4th Semester

Prepared By
JAVID AHMAD PARRAY
Assistant Professor
Department of Computer Science
IQBAL INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Laloo Sheshgaribagh Hyderpora Srinagar – 190014

1 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

UNIT – I
Procedure Oriented Programming Language
In the procedure oriented approach, the problem is viewed as sequence of things to be
done such as reading, calculating and printing.

Procedure oriented programming basically consist of writing a list of instruction or


actions for the computer to follow and organizing these instruction into groups known as
functions.

Main program

Function-1 Function-2 Function-3

The disadvantage of the procedure oriented programming languages is:


1. Global data access
2. It does not model real word problem very well
3. No data hiding

Global data Global data

Function-1 Function-2 Function-3

Local data Local data Local data

Characteristics of procedure oriented programming


1. Emphasis is on doing things(algorithm)
2. Large programs are divided into smaller programs known as functions.
3. Most of the functions share global data
4. Data move openly around the system from function to function
5. Function transforms data from one form to another.
6. Employs top-down approach in program design

2 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Object Oriented Programing


Object-Oriented Programming is a programming paradigm based on the concept of objects,
which can contain data and code. The data is in the form of fields, and the code is in the
form of procedures.
A common feature of objects is that procedures are attached to them and can access and
modify the object’s data fields.
Object A Object B

Data Data

Communication

Functions Functions

Object C

Functions

Data

Features of the Object Oriented programming


1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on the data of an object are tied together in the data
structure.
5. Data is hidden and can’t be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added.
8. Follows bottom-up approach in program design.

3 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Difference Between Procedure Oriented Programming (POP) & Object


Oriented Programming (OOP)
S. No Procedure Oriented Programming Object Oriented Programming
1 Program is divided into Program is divided into parts called
small parts called functions. objects.
Importance is not given to Importance is given to the data
2 data but to functions as well as rather than procedures or functions
sequence of actions to be because it works as a real world.
done.
3 follows Top Down approach. OOP follows Bottom Up approach.
4 OOP has access specifiers
It does not have any access
named Public, Private,
specifier.
Protected.
5 Data can move freely from objects can move and
function to function in the communicate with each other
system. through member functions.
6 To add new data and OOP provides an easy way to add
function in POP is not so new data and function.
easy.
7 Most function uses Global In OOP, data can not move easily
data for sharing that can be from function to function, it can
accessed freely from be kept public or private so we
function to function in the can control the access of data.
system.
8 It does not have any proper OOP provides Data Hiding so
way for hiding data so it is provides more security.
less secure.
9 Overloading is not possible. In OOP, overloading is possible
in the form of Function
Overloading and Operator
Overloading.
10 Example of Procedure Example of Object Oriented
Oriented Programming are : C++, JAVA,
Programming are : C, VB, VB.NET, C#.NET.
FORTRAN, Pascal.

4 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Benefits of OOP

 Reusability: In OOP’s programs, functions and modules that are written by a user
can be reused by other users without any modification.
 Inheritance: Through this we can eliminate redundant code and extend the use of
existing classes.
 Data Hiding: The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secure programs.

 Reduced complexity of a program: The given problem can be viewed as a


collection of different objects. Each object is responsible for a specific task. The
problem is solved by interfacing the objects. This technique reduces the complexity
of the program design.

 Easy to Maintain and Upgrade: OOP makes it easy to maintain and modify existing
code as new objects can be created with small differences to existing ones. Software
complexity can be easily managed.

 Message Passing: The technique of message passing between objects makes the
interface with external systems easier.

 Modifiability: it is easy to make minor changes in the data representation or the


procedures in an OO program. Changes inside a class do not affect any other part
of a program, since the only public interface that the external world has to a class is
through the use of methods.

Basic Concepts of Object oriented Programming


1. Class
2. Object
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing

5 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Class
The building block of C++ that leads to Object-Oriented programming is a Class. 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. For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the class, and wheels,
speed limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage, etc and
member functions can apply brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of objects which shares
some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and behavior. An Object is an
instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
Objects take up space in memory and have an associated address like a record in pascal or
structure or union. When a program is executed the objects interact by sending messages to
one another. Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to know the type
of message accepted and the type of response returned by the objects.
6 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

Encapsulation
Wrapping of data and functions together as a single unit is known as encapsulation. By default
data is not accessible to outside world and they are only accessible through the functions
which are wrapped in a class. prevention of data direct access by the program is called data
hiding or information hiding.
Consider a real-life example of encapsulation, in a company, there are different sections like
the accounts section, finance section, sales section, etc. The finance section handles all the
financial transactions and keeps records of all the data related to finance. Similarly, the sales
section handles all the sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the finance section needs all the
data about sales in a particular month. In this case, he is not allowed to directly access the
data of the sales section. He will first have to contact some other officer in the sales section
and then request him to give the particular data. This is what encapsulation is. Here the data
of the sales section and the employees that can manipulate them are wrapped under a single
name “sales section”.

Encapsulation in C++

Abstraction
Abstraction refers to the act of representing essential features without including the back
ground details or explanation. Classes use the concept of abstraction and are defined as a list
of attributes such as size, weight, cost and functions to operate on these attributes. They
encapsulate all essential properties of the object that are to be created. The attributes are
called as data members as they hold data and the functions which operate on these data are
called as member functions.
Class use the concept of data abstraction so they are called abstract data type (ADT).
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does
not know how on pressing the accelerator the speed is actually increasing, he does not know
about the inner mechanism of the car or the implementation of an accelerator, brakes, etc.
in the car. This is what abstraction is.
 Abstraction using Classes: We can implement Abstraction in C++ using classes. The
class helps us to group data members and member functions using available access
7 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
 Abstraction in Header files: One more type of abstraction in C++ can be header files.
For example, consider the pow() method present in math.h header file. Whenever we
need to calculate the power of a number, we simply call the function pow() present in
the math.h header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually calculating the power
of numbers.

Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A person
at the same time can have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different behavior in different
situations. This is called polymorphism. An operation may exhibit different behaviors in
different instances. The behavior depends upon the type of data used in the operation.
Different ways to achieving polymorphism in C++ program.
 Operator Overloading: The process of making an operator exhibit different behaviors in
different instances is known as operator overloading.
 Function Overloading: Function overloading is using a single function name to perform
different types of tasks. Polymorphism is extensively used in implementing inheritance.

Inheritance
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
 Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
 Super Class: The class whose properties are inherited by a sub-class is called Base Class
or Superclass.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

8 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Inheritance in C++

Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at
run time. C++ has virtual functions to support this. Because dynamic binding is flexible, it
avoids the drawbacks of static binding, which connected the function call and definition at
build time.
Message Passing
Objects communicate with one another by sending and receiving information. A message
for an object is a request for the execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function, and the information to be sent.
Employee . Salary (name)

Object Information
Message

9 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Difference Between C and C++

C C++
C was developed in 1972 by Dennis Ritchie C++ was developed by Bjarne Stroustrup
at Bell Laboratories. at Bell Laboratories in the early 1980s.
It is a function-driven language. It is an object-driven language.
C++ is both a procedural and an object-
C is a Procedural Oriented language. It does
oriented programming language. It
not support object-oriented programming
supports OOP features such as
(OOP) features such as polymorphism,
polymorphism, encapsulation, and
encapsulation, and inheritance.
inheritance.
C is a subset of C++. C++ is a superset of C.

C has 32 keywords. C++ has 63 keywords.


The file extension of a program in C The file extension of a C++ program is
language is .c. .cpp.
Does not have access modifiers. Has access modifiers.
C uses <stdio.h> header file for input/output C++ uses <iostream.h> header file for
operations. input/output operations.
Data is secured and hidden by
No support for information hiding.
Encapsulation.
C focuses on the method or procedure rather C++ focuses on data rather than method
than data. or procedure.
C uses scanf() and printf() functions for
C++ uses cin and cout for input/output.
input/output.
Does not support function and operator Supports function and operator
overloading. overloading.
Does not support any reference variables. Supports reference variables.

C++ Tokens
A token represents the smallest meaningful component recognized by the compiler in a
program. It corresponds to a specific element or idea within the programming language.
Tokens are fundamental building blocks for the language and are utilized for creating valid
expressions and statements.
Following are the C++ tokens : (most of c++ tokens are basically similar to the C tokens)

10 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

 Keywords
 Identifiers
 Variables
 Constants
 Operators

Keywords
Keywords in C++ are the tokens that are the reserved words in programming language that
have their specific meaning and functionalities within a program. Keywords cannot be used
as an identifier to name any variables.
The following table shows the standard C++ keywords

auto break case char const continue


default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while class friend new delete
this public private protected inline try
throw catch template

Identifiers
Identifiers are the names given to various program elements such as variables, functions ,
arrays and other user-defined data types created by the programmer. These are user
defined names consisting of sequence of letters and digits.

Rules for declaring identifiers:

 The first character must be an alphabet or underscore.


 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.

11 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

 Upper and lower case letters are different.

Example: ab, Ab, aB, AB are treated differently

Examples of valid identifiers:


a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1
Examples of Invalid identifiers:

$amount, grand-total, sum of digits, 4num.


$amount: Special character is not permitted

grand-total: hyphen is not permitted


sum of digits: blank spaces between the words are not allowed.
4num: should not start with a number (first character must be a letter or underscore)

Variables
Variable in C++ is a name given to a memory location. It is the basic unit of storage in a
program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.

For example

int age = 14;

Here, age is a variable of the int data type, and we have assigned an integer value 14 to it.

The value of a variable can be changed, hence the name variable.

int age = 14; // age is 14

age = 17; // age is 17

12 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Rules for naming a variable

 A variable name can only have alphabets, numbers, and the underscore _.

 A variable name cannot begin with a number.

 It is a preferred practice to begin variable names with a lowercase character. For


example, name is preferable to Name.

 A variable name cannot be a keyword. For example, int is a keyword that is used to
denote integers.

 A variable name can start with an underscore. However, it's not considered a good
practice.

Declaration of a Variable
A variable is introduced into a program by a declaration which states its type (i.e int, float,
bool or char) and its name, which you are free to choose.

A declaration must take the form:


type variable-name;
int count;
float length;
char firstInitial;
bool switched_on;
or:
type variable1, variable2, ... variableN;
float base, height, areaCircle;
int myAge, number_throws;

C++ Constants/Literals
Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be
modified after their definition.

13 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order.
Here are some examples of integer literals
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
Following are other examples of various types of Integer literals
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing using decimal form, you must include the decimal point, the exponent,
or both and while representing using exponential form, you must include the integer part, the
fractional part, or both. The signed exponent is introduced by e or E.
Here are some examples of floating-point literals
3.14159 // Legal
314159E-5L // Legal
510E // Illegal: incomplete exponent
210f // Illegal: no decimal or exponent
.e55 // Illegal: missing integer or fraction

Boolean Literals

There are two Boolean literals and they are part of standard C++ keywords

14 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

 A value of true representing true.


 A value of false representing false.
You should not consider the value of true equal to 1 and value of false equal to 0.

Character Literals

Character literals are used to assign a fixed value to characters including alphabets and
digits or special symbols enclosed within single quotation marks( ‘ ’ ).
Each character is associated with its specific numerical value called the ASCII (American
Standard Code For Information Interchange) value.

For example, ‘+’, ‘A’, ‘d’.


There are certain characters in C++ when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a
list of some of such escape sequence codes

Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

15 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

Following is the example to show a few escape sequence characters


Live Demo
#include <iostream>
using namespace std;
int main() {
cout << "Hello\tWorld\n\n";
return 0;
}

When the above code is compiled and executed, it produces the following result
Hello World

String Literals
String literals are enclosed in double quotes. A string contains characters that are similar to
character literals, plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separate them using
whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"

"hello, \

dear"

"hello, " "d" "ear"

16 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Defining Constants
There are two simple ways in C++ to define constants
 Using #define preprocessor.
 Using const keyword.

The #define Preprocessor

Following is the form to use #define preprocessor to define a constant


#define identifier value
Following example explains it in detail
Live Demo
#include <iostream>
using namespace std;
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}

When the above code is compiled and executed, it produces the following result
50

The const Keyword

You can use const prefix to declare constants with a specific type as follows
const type variable = value;

17 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Following example explains it in detail


Live Demo
#include <iostream>
using namespace std;
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
}

When the above code is compiled and executed, it produces the following result
50
Note that it is a good programming practice to define constants in CAPITALS.

Reference variables
Reference variable is an alternative name of already existing variable. It cannot be changed
to refer another variable and should be initialized at the time of declaration and cannot be
NULL. The operator ‘&’ is used to declare reference variable.

The following is the syntax of reference variable.

datatype variable_name; // variable declaration


datatype& refer_var = variable_name; // reference variable
Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.

18 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

refer_var − The name of reference variable.


Why Use Reference Variables?
1. Simplicity: Reference variables provide a simpler syntax for accessing and
modifying variables.
2. Avoiding Copies: They allow for passing large objects to functions without
copying, enhancing performance.
3. Function Parameters: They can be used as function parameters to allow functions
to modify the arguments passed to them.
Example: C++ Reference
#include <iostream>
using namespace std;
int main() {
string city = "Paris";
// create a reference to the variable
string& ref_city = city;
// display the variable
cout << "Variable Value: " << city << endl;
cout << "Reference Value: " << ref_city << endl;
return 0;
}
Output
Variable Value: Paris
Reference Value: Paris
In the above example, we have used the reference variable ref_city to display the value of
the variable city.
Modify Variables Using References
We can modify a variable by simply assigning a new value to the reference variable.
For example
#include <iostream>
using namespace std;

19 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

int main() {
string city = "Paris";
// create a reference to the variable
string& ref_city = city;
// display the variable
cout << "Variable Value = " << city << endl;
cout << "Reference Value = " << ref_city << endl;
// modify the variable using reference
ref_city = "New York";
// display the variable
cout << endl << "After Modification: " << endl;
cout << "Variable Value = " << city << endl;
cout << "Reference Value = " << ref_city << endl;
return 0;
}
Output
Variable Value: Paris
Reference Value: Paris
After Modification:
Variable Value: = New York
Reference Value: New York

C++ Basic 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.
The C++ programming language supports the following basic data types.

1. Character Data Type (char)

20 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

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
#include <iostream>
using namespace std;
int main() {
// Character variable
char c = 'A';
cout << c;
return 0;
}
Output
A
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

21 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

int x = 25;
cout << x << endl;
// Using hexadecimal base value
x = 0x15;
cout << x;
return 0;
}
Output
25
21

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>
using namespace std;
int main() {
// Creating a boolean variable
bool isTrue = true;
cout << isTrue;
return 0;
}
Output
1

22 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

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.
Example
#include <iostream>
using namespace std;
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;
where, name is the identifier assigned to the variable.
Example
#include <iostream>
using namespace std;
int main() {
// double precision floating point variable

23 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

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() {
cout << "Hello, World!" << endl;
}
int main() {
hello();
return 0;
}
Output
Hello, World!
Size of Data Types in C++
The size of C++ data types can vary across different systems, depending on the architecture
of the computer (e.g., 32-bit vs. 64-bit systems) and the compiler being used. But if the
architecture of the computer is same, then the size across different computers remains same.
We can find the size of the data type using sizeof operator.
Example:
24 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

#include <iostream>
using namespace std;
int main() {
// Printing the size of each data type
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " byte" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes";
return 0;
}
Output
Size of int: 4 bytes
Size of char: 1 byte
Size of float: 4 bytes
Size of double: 8 bytes

Data Type Modifiers


Data type modifiers are the keywords used to change or give extra meaning to already
existing data types. It is added to primitive data types as a prefix to modify their size or range
of data they can store. There are 4 type modifiers in C++: short, long, signed and unsigned.

C++ Modified Data Types List

Size (in
Data Type Meaning
Bytes)

signed int 4 used for integers (equivalent to int)

unsigned int 4 can only store positive integers

used for small integers (range -32768 to


short 2
32767)

25 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

used for small positive integers (range 0 to


unsigned short 2
65,535)

long at least 4 used for large integers (equivalent to long int)

used for large positive integers or 0 (equivalent


unsigned long 4 or 8
to unsigned long int)

used for very large integers (equivalent to long


long long 8
long int).

unsigned long used for very large positive integers or 0


8
long (equivalent to unsigned long long int)

long double 8, 12, or 16 used for large floating-point numbers

used for characters (guaranteed range -127 to


signed char 1
127)

unsigned char 1 used for characters (range 0 to 255)

Streams in C++
A stream is a sequence of bytes. It acts either as a source from which the input data can be
obtained or as a destination to which the output data can be sent. The source stream that
provides data to the program is called Input Stream and the destination stream that receives
output from the program is called Output Stream.
In C++, the I/O system contains a hierarchy of classes that are used to define various streams
to deal with both the console and disk files. These classes are called stream classes. The
stream classes are used for input and output operations with the console unit. These classes
are declared in the header file iostream. This file should be included in all the programs that
communicate with the console unit.
The class ios is declared as the virtual base class so that only one copy of its members is
inherited by the iostream. The class ios provides the basic support for formatted and
unformatted I/O operations. The class istream provides the facilities for formatted and
unformatted input while the class ostream provides the facilities for formatted output.

26 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

The class iostream provides the facilities for handling both input and output streams. Three
classes namely, istream_withassign, ostream_withassign and iostream_withassign is used to
add assignment operators to these classes.

Stream Classes for Console Operations:


ios: It contains basic facilities that are used by all other input and output classes. It also
contains a pointer to a buffer object (streambuf object). It declares constants and functions
that are necessary for handling formatted input and output operations.
istream: It inherits the properties of ios. It declares input functions such as get(), getline()
and read(). It contains overloaded extraction operator >>.
ostream: It inherits the properties of ios. It declares output functions put() and write(). It
contains overloaded insertion operator <<.
iostream: It inherits the properties of ios istream and ostream through multiple inheritances
and thus contains all the input and output functions.
streambuf: It provides an interface to physical devices through buffers. It acts as a base for
filebuf class used ios files.

Unformatted I/O Operations in C++


Unformatted I/O Operations are used for performing input/output operations at the console
and the resulting data is left unformatted.

Overloaded Operators>>and<<
We have used the objects cin and cout for the input and output of data of various types.
The >> operator is overloaded in the istream class and << is overloaded in the ostream class.
It has the following syntax:

cin>>variable1>>variable2>>.....variablen

put() and get() functions:


The classes istream and ostream define two member functions get() and put() is used to
handle the single character input/output operations. There are two types of get() functions.
We can use both get(char*) and get(void) prototype to fetch a character including the blank
space, tab and the newline character. The get(char*) version assigns the input character to its
argument and the get(void) version returns the input character.
Example:
char c;
cin.get(c); // get a character from keyboard and assign it to c
while(c!='\n')
{
27 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

cout<<c;
cin.get(c); // get another character
}

Formatted I/O Operations in C++


C++ supports a number of features that could be used for formatting the output. These
features include:
 ios class functions and flags
 Manipulators
 User-defined output functions

The ios class contains a large number of member functions that would help us to format the
output in some ways.

Function Task

width() It specifies the required field size for displaying an output value.
It specifies the number of digits to be displayed after the decimal point of
precision()
a float value.
fill() It specifies a character that is used to fill the unused portion of a field.

setf() It specifies format flags that can control the form of the output display.

unsetf() It is used to clear the flags specified.

C++ Manipulators
Manipulators are special functions that can be included in the I/O statements to alter the
format parameters of a stream.

Manipulators Task
It is used to specify the required field size for displaying an output
setw()
value.
It is used to specify the number of digits to be displayed after the
setprecision()
decimal point of a float value.

28 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

It is used to specify a character that is used to fill the unused portion of


setfill()
a field.
It is used to specify format flags that can control the form of the output
setiosflags()
display.
resetiosflags() It is used to clear the flags specified.

C++ Operators
The C++ programming language provides a wide range of operators to perform mathematical,
logical, and other operations. An operator is a symbol used to perform mathematical and
logical operations. Every operator has a pre-defined functionality. However, C++ language
provides a concept operator overloading to assign user-defined functionality to most of the
operators.
In C++ language, the operators are classified as follows.

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Increment and Decrement Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators
 Scope Resolution Operator
 Other Operators

Arithmetic Operators (+, -, *, /, %)


The arithmetic operators are the symbols that are used to perform basic mathematical
operations like addition, subtraction, multiplication, division and percentage modulo. The
following table provides information about arithmetic operators.
Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

29 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

% Remainder of the Division 5%2=1

Relational Operators (<, >, <=, >=, ==, !=)


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used
to define conditions in a program. The following table provides information about relational
operators.
Operator Meaning Example

< Returns TRUE if the first value is smaller than second 10 < 5 is FALSE
value otherwise returns FALSE

> Returns TRUE if the first value is larger than second value 10 > 5 is TRUE
otherwise returns FALSE

<= Returns TRUE if the first value is smaller than or equal to 10 <= 5 is
second value otherwise returns FALSE FALSE

>= Returns TRUE if the first value is larger than or equal to 10 >= 5 is TRUE
second value otherwise returns FALSE

== Returns TRUE if both values are equal otherwise returns 10 == 5 is


FALSE FALSE

!= Returns TRUE if both values are not equal otherwise 10 != 5 is TRUE


returns FALSE

Logical Operators (&&, ||, !)


The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
Operator Meaning Example

&& Logical AND - Returns TRUE if all conditions 10 < 5 && 12 > 10 is
are TRUE otherwise returns FALSE FALSE

30 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

|| Logical OR - Returns FALSE if all conditions 10 < 5 || 12 > 10 is TRUE


are FALSE otherwise returns TRUE

! Logical NOT - Returns TRUE if condition is !(10 < 5 && 12 > 10) is
FLASE and returns FALSE if it is TRUE TRUE

Increment & Decrement Operators (++ & --)


The increment and decrement operators are called unary operators because both need only
one operand. The increment operator adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand. The following table
provides information about increment and decrement operators.
Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


a++; ⇒ a = 6

-- Decrement - Subtracts one from existing value int a = 5;


a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-
decrement.

Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In the case of pre-decrement, the value of the variable is decreased by
one before the expression evaluation. That means, when we use pre-increment or pre-
decrement, first the value of the variable is incremented or decremented by one, then the
modified value is used in the expression evaluation.
Example
#include <iostream>

using namespace std;

int main()

{
31 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

int i = 5, j;

j = ++i; // Pre-Increment

cout << "i = " << i << ", j = " << j << endl;

return 0;

When we run the above example code, it produces the following output.

Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after
the expression evaluation. That means, when we use post-increment or post-decrement, first
the expression is evaluated with existing value, then the value of the variable is incremented
or decremented by one.
Example
#include <iostream>

using namespace std;

int main()

int i = 5, j;

j = i++; // Post-Increment

cout << "i = " << i << ", j = " << j << endl;
32 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

return 0;

When we run the above example code, it produces the following output.

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators.
Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result A += 10
into left-hand side variable ⇒ A = A+10

-= Subtract right-hand side value from left-hand side variable A -= B


value and store the result into left-hand side variable ⇒ A = A-B

*= Multiply right-hand side value with left-hand side variable A *= B


value and store the result into left-hand side variable ⇒ A = A*B

/= Divide left-hand side variable value with right-hand side A /= B


variable value and store the result into the left-hand side ⇒ A = A/B
variable

%= Divide left-hand side variable value with right-hand side A %= B


variable value and store the remainder into the left-hand side ⇒ A = A%B
variable

33 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language.
When we use the bitwise operators, the operations are performed based on the binary values.
The following table describes all the bitwise operators.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).


Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise A&B
it is 0 ⇒ 16 (10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it A|B


is 1 ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)

~ the result of Bitwise one’s complement is negation of the bit ~A


(Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by A << 2
the specified number of positions ⇒ 100 (1100100)

>> the Bitwise right shift operator shifts all the bits to the right A >> 2
by the specified number of positions ⇒ 6 (00110)

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first we verify a condition, then
we perform one operation out of the two operations based on the condition result. If the
condition is TRUE the first option is performed, if the condition is FALSE the second option
is performed. The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;


Example

34 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

A = (10<15)? 100 : 200; // ⇒ A value is 100

Scope Resolution Operator (: :)


The scope resolution operator in C++ is used to access the global variable when both local
and global variables are having the same name, to refer to the static members of a class, and
to define a function definition outside the class.

Special Operators (sizeof, pointer, comma, dot, etc.)


The following are the special operators in C++ programming language.

sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.
sizeof(variableName);
Example

sizeof(A); // ⇒ the result is 2 if A is an integer

Pointer operator (*)


This operator is used to define pointer variables.

Comma operator (,)


This operator is used to separate variables while they are declaring, separate the expressions
in function calls etc.

Dot operator (.)


This operator is used to access members of a class, and structure.
The operators are also classified based on the number of operands required by the operator.
 Unary Operators
Requires only one operand like ++ and --.
 Binary Operators
Requires two operands like +, *, ==, ||, >> etc.
 Ternary Operators
Requires three operands like conditional operator.

35 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Precedence and associativity of Operators in C++


The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right
to left.

Let's understand the precedence by the example given below:

int data=5+10*10;

The "data" variable will contain 105 because * (multiplicative operator) is evaluated before
+ (additive operator).

The precedence and associativity of C++ operators is given below:

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

36 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ decision making statements


The selection (if, if-else, if-else-if, and switch) statements allows to choose the set-of-
instructions for execution depending upon an expression's truth value. C++ provides
following two types of selection statements:
 if statement
 switch statement
The selection statements are also called conditional statements or decision statements. We
will learn about selection statements of C++ in detail, divided into these parts:
 if statement
 if-else statement
 nested ifs statement
 if-else-if ladder
 switch statement
 nested switch statement
C++ if Statement
An if statement tests a particular condition; if the condition evaluates to true, a course-of-
action is followed i.e., a statement or set-of-statements is executed. Otherwise (if the
condition evaluates to false), the course-of-action is ignored. Here is the syntax or general
form of the if statement:
if(expression)
{
statement(s);
}

Here, statement may be a single statement or a block of statements, or nothing (in case of
empty statement). The expression must be enclosed in parentheses. If the expression evaluates
to true i.e., a nonzero value, the statement is executed, otherwise ignored. For example, the
following code fragment :

if(ch == ' ')


{
spaces++;
}

Checks whether the character variable ch stores a space or not; if it does, the number of spaces
are incremented by 1. Consider another example illustrating the use of if statement:

37 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

char ch;
cin >> ch;
if(ch == ' ')
{
cout << "You entered a space" << "\n" ;
}
if(ch >= '0' && ch <= '9')
{
cout << "You entered a digit" << "\n";
}

The above example reads a character. If the character input is a space, if flashes a message
specifying it. If the character input is a digit, it flashes a message specifying it. Let's take an
example demonstrating the if statement of C++ practically.

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch>='0' && ch<='9')
{
cout<<"You entered a digit.";
}
getch();
}

Here is the sample run of the above C++ program:

38 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Let's take another example, also demonstrating the if statement of C++

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2==0)
{
cout<<"You entered an even number";
}
getch();
}

Here is the sample run of this C++ program:

Following example programs also illustrates the syntax and working of the if statement:

/* C++ Selection Statements - C++ if Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, y, z, max;
cout<<"Enter any three numbers: ";
cin>>x>>y>>z;
max = x;

39 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

if(y>max)
{
max = y;
}
if(z>max)
{
max = z;
}
cout<<"\n"<<"The largest of "<<x<<", "<<y<<" and "<<z<<" is "<<max;
getch();
}

When the above C++ program is compile and executed, it will produce the following
output. This is the output, if 3rd number is biggest.

Here is another output, if 2nd number is biggest.

Now, here is the last output, if 1st number is biggest:

40 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ if-else Statement


The examples of if statement, you have seen so far allow you to execute a set of statements
if a condition or expression evaluates to true. What if there is another course of action to be
followed if the expression evaluates to false ?

There is another form of if that allows for this kind of either-or condition by providing an
else clause. The syntax of the if-else statement is the following:

if(expression)
{
statement 1;
}
else
{
statement 2;
}

If the expression evaluates to true i.e., a nonzero value, the statement 1 is executed, otherwise,
statement 2 is executed. The statement 1 and statement 2 can be a single statement, or a
compound statement, or a null statement.

Note - Remember, in an if-else statement, only the code associated with if (i.e., statement 1)
or the code associated with else (i.e., statement 2) executes, never both.

Let's take an example program, demonstrating the if-else statement of C++, practically.

/* C++ Selection Statements - C++ if-else Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num%2==0)
{
cout<<"You entered an even number";
}
else
41 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

{
cout<<"You entered an odd number";
}
getch();
}

Below are the two sample run of the above C++ program:

Here is another program, also illustrating the use of if-else statement in a C++ program:

/* C++ Selection Statements - C++ if-else Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, y ;
cout<<"Enter two numbers: ";
cin>>x>>y;
if(x>y)
{
cout<<x<<" is largest";
}
else
{
cout<<y<<" is largest";

42 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

}
getch();
}

When the above C++ program is compile and executed, it will produce the following
output:

C++ Nested Ifs Statement


A nested if is an if that has another if in its if's body or in its else's body. The nested if can
have one of the following three forms. Here is the first form:
if(expression 1)
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
body-of-else;
}

This is the second form of nested ifs statement

if(expression 1)
{
body-of-if;
else
{

43 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
}

Now, this is the third form of nested ifs statement

if(expression 1)
{
if(expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
if(expression 3)
{
statement 3;
}
else
{
statement 4;
}
}

In an if statement, either there can be if statement(s) in its body-of-if or in its body-of-else or


in both. The inner ifs can themselves be nested ifs, but the inner if must terminate before an
outer if. Following example programs illustrates the use of nested ifs

44 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

/* C++ Selection Statements - C++ nested ifs Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<"Enter a number: ";
cin>>num;
if(num>100)
{
if(num>500)
{
if(num>10000)
{
cout<<"Its too high..!!";
}
if(num<1000)
{
cout<<"Its medium..!!";
}
}
if(num<=500)
{
cout<<"Its low..!!";
}
}
if(num<=100)
{
cout<<"Its too low..!!";
}
getch();
}

Here are the sample runs of the above C++ program:

45 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ if-else-if Ladder


A common programming construct in C++ is the if-else-if ladder, which is often also called
the if-else-if staircase because of its appearance. It takes the following general form:
if(expression)
{
statement 1;
}
else if(expression 2)
{
statement 2;
}
else if(expression 3)
{
statement 3;
}
.
.
.
else
{
statement N;
}

The expression are evaluated from the top downward. As soon as an expression evaluates to
true, the statement associated with it is executed and the rest of the ladder is bypassed. If none
of the expression are true, the final else gets executed. If the final else is missing, no action

46 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

takes place if all the conditions are false. Following are some examples illustrates the use of
if-else-if ladder in a C++ program:

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
float a, b, result;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
cin>>ch;
cout<<"\n";
if(ch=='+')
result=a+b;
else
if(ch=='-')
result=a-b;
else
if(ch=='*')
result=a*b;
else
if(ch=='/')
result=a/b;
cout<<"\n"<<"The calculated result is : "<<result<<"\n";
getch();
}

Here are the two sample runs of the above C++ program:

47 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Here is the improved version of the above C++ program.

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
float a, b, result;
cout<<"Enter any two number: ";
cin>>a>>b;
cout<<"\n"<<"Enter the operator(+, -, *, /) : ";
cin>>ch;
cout<<"\n";
if(ch=='+')
{
result=a+b;
}
else if(ch=='-')

48 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

{
result=a-b;
}
else if(ch=='*')
{
result=a*b;
}
else if(ch=='/')
{
result=a/b;
}
else
{
cout<<"Wrong Operator..!!.. exiting...press a key..";
getch();
exit(1);
}
cout<<"\n"<<"The calculated result is : "<<result<<"\n";
getch();
}

When the above C++ program is compile and run, it will produce the following outputs:

Here is another sample run of the above C++ program:

49 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Here is one more sample run of the above C++ program:

Let's take another C++ program, for the complete understanding on the if-else-if ladder in
C++. Before going to this program, let's see the following table to understand the ASCII code
for different character. Because the upcoming program print whether a given character is an
upper case or a lower case character or a digit or any other character. Use the ASCII codes
for it. The ASCII codes are given here in the following table:

Characters ASCII Range

'0' - '9' 48 – 57

'A' - 'Z' 65 – 90

'a' - 'z' 97 – 122

Other Characters 0 - 255 excluding the above mentioned codes

50 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Let's now look at the following program:

/* C++ Selection Statements - C++ if-else-if Ladder */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
cout<<"Enter a character: ";
cin>>ch;
if(ch >= 48 && ch <= 57)
{
cout<<"\nYou entered a digit";
}
else if(ch >= 65 && ch <= 90)
{
cout<<"\nYou entered an uppercase character";
}
else if(ch >= 97 && ch <=122)
{
cout<<"\nYou entered a lowercase character";
}
else
{
cout<<"\nYou entered a special character";
}
getch();
}

When the above program is compile and executed, it will produce the following output:

51 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

The ? : (Alternative to if)


C++ has an operator that can be used as an alternative to if statement. You are familiar with
this operator, the conditional operator ? : This operator can be used to replace if-else
statements of the general form:
if(expression1)
{
expression2;
}
else
{
expression3;
}

The above form of if can be alternatively written using ? : as follows,

expression1 ? expression2 : expression3 ;

It works in the same way as the above given form of if does i.e., expression1 is evaluated, if
it is true, expression2 gets executed (i.e., its value becomes the value of entire expression)
otherwise expression3 gets executed (i.e., its value now becomes the value of the entire
expression). For example, the following if statement:

int c;
if(a>b)
{

52 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

c=a;
}
else
{
c=b;
}

can be alternatively written as

int c = a > b ? a : b ;

See how simple and compact your code has become.

C++ switch Statement


C++ provides a multiple-branch selection statement known as switch. This selection
statement successively tests the value of an expression against a list of integer or character
constants. When a match is found, the statements associated with that constant are executed.
The syntax of switch statement is as follows:
switch(expression)
{
case constant1: statement sequence 1;
break;
case constant2: statement sequence 2;
break;
case constant3: statement sequence 3;
break;
.
.
.
case constant n-1: statement sequence n-1;
break;
default: statement sequence n;
}

The expression is evaluated and its values are matched against the values of the constants
specified in the case statements. When a match is found, the statement sequence associated
with that case is executed until the break statement or the end of switch statement is reached.
If a case statement does not include a break statement, then the control continues right on the
next case statement(s) until either a break is encountered or end of switch is reached. This
situation (i.e., missing break in case statement) is called fall through. The default statement

53 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

gets executed when no match is found. The default statement is optional and, if it is missing
, no action takes place if all matches fail.

The ANSI standard specifies that a switch can have upto 257 case statements, however, you
must always limit the number of case statements to a smaller amount for the sake of
efficiency.

Following example illustrates the use of switch statement. This program ask to the user to
input number of week's day (1-7) and translate to its equivalent name of the day of the week
(e.g., 1 to Sunday, 2 to Monday, ...., 7 to Saturday).

/* C++ Selection Statement - C++ switch Statement */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int dow;
cout<<"Enter number of week's day (1-7): ";
cin>>dow;
switch(dow)
{
case 1: cout<<"\nSunday";
break;
case 2: cout<<"\nMonday";
break;
case 3: cout<<"\nTuesday";
break;
case 4: cout<<"\nWednesday";
break;
case 5: cout<<"\nThursday";
break;
case 6: cout<<"\nFriday";
break;
case 7: cout<<"\nSaturday";
break;
default: cout<<"\nWrong number of day";
break;
}

54 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

getch();
}

When the above program is compile and executed, it will produce the following output:

Here is another sample output of the above C++ program:

switch Vs if-else
The switch and if-else both are selection statements and they both let you select an alternative
out of given many alternatives by testing an expression. However, there are some differences
in their operations. These are given below:

 The switch statement differs from the if statement in that switch can only test for
equality whereas if can evaluate a relational or logical expression i.e., multiple
conditions.
 The switch statement selects its branches by testing the value of same variable (against
a set of constants) whereas the if-else construction lets you use a series of expressions
that may involve unrelated variables and complex expressions.
 The if-else is more versatile of the two statements. For example, if-else can handle
ranges whereas switch cannot. Each switch case label must be a single value.
 The if-else statement can handle floating-point tests also apart from handling integer
and character tests whereas a switch cannot handle floating-point tests. The case labels
of switch must be an integer (which includes char also).

55 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

 The switch case label value must be a constant. So, if two or more variables are to be
compared, use if-else.
 The switch statement is more efficient choice in terms of code used in a situation that
supports the nature of switch operation (testing a value against a set of constants).

C++ Nested-Switch
Like if statements, a switch can also be nested. There can be a switch as part of the statement
sequence of another switch. For example, the following code fragment is perfectly all right in
C++.

switch(a)
{
case 1: switch(b)
{
case 0: cout << "Divide by zero-Error !!" ;
break;
case 1: res = a/b ;
}
break;
case 2:
:
}

Some important Things to know about switch


There are some important things that you must know about the switch statement:

 A switch statement can only work for equality comparisons.


 No two case labels in the same switch can have identical values. But, in case of
nested switch statements the case constants of the inner and outer switch can contains
common values.
 If character constants are used in the switch statement, they are automatically
converted to their integers (i.e., their equivalent ASCII codes).
 The switch statement is more efficient than if in a situation that supports the nature of
switch operation.

Example: C++ program to check for zero or non-zero and odd or even using nested switch
statement
#include <iostream>
using namespace std;
56 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

int main()
{
int a = 8;
cout<<"The Number is : " <<a <<endl;
switch (a)
{
case 0 :
cout<<"The number is zero" <<endl;
break;
default:
cout<<"The number is a non-zero integer" <<endl;
int b = a % 2;
switch (b)
{
case 0:
cout<<"The number is even" <<endl;
break;
case 1:
cout<<"The number is odd" <<endl;
break;
}
}
return 0;
}

Output
The Number is : 8
The number is a non-zero integer
The number is even

57 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ loops
The iteration (for, while, and do-while loop) statements allows a set of instruction to be
performed repeatedly until a certain condition is fulfilled. The iteration statements are also
called loops or looping statements. C++ provides three kinds of loops:
 for loop
 while loop
 do-while loop
All three loop constructs of C++ repeat a set of statements as long as a specified condition
remains true. This specified condition is generally referred to as a loop control. For all three
loop statements, a true condition is any nonzero value. A zero value indicates a false
condition.
Loop Parts
Every loop has its elements that control and govern its execution. Generally, a loop has four
elements that have different purposes. These elements are as:
 Initialization Expression(s)
 Test Expression
 Update Expression(s)
 Loop's Body
Initialization Expression(s)
Before entering in a loop, its control variable(s) must be initialized. The initialization of the
control variable(s) takes place under initialization expression(s). The initialization
expression(s) give(s) the loop variable(s) their first value(s). The initialization expression(s)
is executed only once, in the beginning of the loop.
Test Expression
The test expression is an expression whose truth value decides whether the loop-body will be
executed or not. If the test expression evaluates to true i.e., 1, the loop-body gets executed,
otherwise the loop is terminated.
In an entry-controlled loop, the test-expression is evaluated before exiting from the loop. In
C++, the for loop and while loop are entry-controlled loops and do-while loop is exit-
controlled loop.
Update Expression(s)
The update expression(s) change the value(s) of loop variable(s). The update expression(s) is
executed; at the end of the loop after the loop-body is executed.

58 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Loop's Body
The statements that are executed repeatedly (as long as the test-expression is nonzero) form
the body of the loop. In an entry-controlled loop, first test-expression is evaluated and if it is
nonzero, the body-of-the-loop is executed; if the test-expression evaluates to be zero, the loop
is terminated. In an exit-controlled loop, the body-of-the-loop is executed first and then the
test-expression is evaluated. If it evaluates to be zero, the loop is terminated otherwise
repeated.

C++ for Loop


The for loop is the easiest to understand of the C++ loops. All its loop-control elements are
gathered in one place (on the top of the loop), while in the other loop construction of C++,
they (top-control elements) are scattered about the program.

C++ for Loop Syntax


The general form (syntax) of the for loop statement is:
for(initialization expression(s); test-expression; update expression(s))
{
body-of-the-loop;
}

C++ for Loop Example


The following example program illustrates the use of for statement:
/* C++ Iteration Statements - C++ for Loop */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i;
for(i=1; i<=10; i++)
{
cout<<i<<" ";
}
getch();
}

When the above program is compile and executed, it will produce the following output:

59 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

The following lines explain the working of the above given for loop program:

 Firstly, initialization expression is executed, i.e., i=1 which gives the first value 1 to
variable i.
 Then, the test expression is evaluated i.e., i <= 10 which results into true i.e., 1.
 Since, the test expression is true, the body-of-the-loop i.e., cout << i << " "; is executed
which prints the current value of i then a single space.
 After executing the loop-body, the update expression i.e., i++ is executed which
increments the value of i. (After first execution of the loop, the value of i becomes 2
after the execution of i++, since initially i was 1).
 After the update expression is executed, the test-expression is again evaluated. If it is
true the sequence is repeated from the step no 3, otherwise the loop terminates.

Note - Use for loop when you have to repeat a block of statements specific number of times.

C++ Infinite Loop


Although any loop statement can be used to create an infinite loop (endless loop) yet for is
traditionally used for this purpose. An infinite for loop can be created by omitting the test-
expression as shown below :
for(i=25; ; i--)
{
cout << "This loop runs forever..!!" ;
}

Similarly, the following for loop is also an infinite loop :

for( ; ; )
{
cout << "I will not stop..!!" ;
}

Here is an example of infinite loop in C++

60 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

/* C++ Loops - C++ Infinite Loop */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for( ; ; )
{
cout<<"This loop will run forever..!!";
}
getch();
}

When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C++ programmers more commonly use the for(;;)
construct to signify an infinite loop. If you try to run the above C++ program, then the output
window will come out like this, printing continuously.

NOTE - You can terminate an infinite loop by pressing Ctrl+C keys. Let's take another
program, prints stars infinite times.

/* C++ Loops - C++ Infinite Loop */

#include<iostream.h>
#include<conio.h>
void main()

61 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

{
clrscr();
for(;;)
{
cout<<"* ";
}
getch();
}

After running this C++ program, output window will look like this, printing stars infinite
times.

C++ Empty Loop


If a loop does not contain any statement in its loop-body, it is said to be an empty loop. In
such cases, a C++ loop contains an empty statement i.e., a null statement. Following for loop
is an empty loop:
for(i=20; (i); i--) ;

See, the body of the above for loop contains just (a null statement). It is an empty loop. An
empty for loop has its applications in pointer manipulations where you need to increment or
decrement pointer position without doing anything else.

Time delay loops are often used in programs. The following code shows how to create one
by using for:

for(t = 0; t < 3000; t++) ;

62 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

That means if you put a semicolon after for's parenthesis it repeats only for counting the
control variable. And if put a block of statements after such a loop, then it is not part of for
loop. For example, consider the following:

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


{
cout << "i = " << i << endl;
}

The semicolon after the for loop ends the loop there only. And then, the below is not body of
the for loop.

C++ while Loop


The second loop available in C++ is the while loop. The while loop is an entry-controlled
loop.

C++ while Loop Syntax


Following is the syntax of the while loop:
while(expression)
{
loop-body;
}

Where the loop-body may contain a single statement, a compound statement or an empty
statement. The loop iterates while the expression evaluates to true. When the expression
becomes false, the program control passes to the line after the loop-body code.

In a while loop, a loop control variable should be initialized before the loop begins as an
uninitialized variable can not be used in the expression. The loop variable should be updated
inside the body-of-the-while.

C++ while Loop Example


Following example program illustrates the working of a while loop:
/* C++ Iteration Statements - C++ while Loop */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();

63 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

unsigned long num, fact=1;


cout<<"Enter a number: ";
cin>>num;
while(num)
{
fact = fact*num;
num--;
}
cout<<"The factorial of the number is "<<fact;
getch();
}

When the above program compile and executed, it will produce the following output:

The above program inputs an integer num. Then as long as num is nonzero (according to
while (num)) the loop-body iterates i.e., fact is multiplied with num and the result is stored
back in fact, followed by the decrement of num. Again the test-expression (num) is evaluated;
if it is true, the loop repeated otherwise terminated.

C++ do-while Loop


Unlike the for and while loops, the do-while is an exit-controlled loop i.e., it evaluates its test-
expression at the bottom of the loop after executing its loop-body statements. This means that
a do-while loop always executes at least once.

In the other two loops for and while, the test-expression is evaluated at the beginning of the
loop i.e., before executing the loop-body. If the test-expression evaluates to false for the first
time itself, the loop is never executed. But in some situations, it is wanted that the loop-body
is executed at least once, no matter what the initial state of the test-expression is. In such
cases, the do-while loop is the obvious choice.

64 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ do-while Loop Syntax

The syntax of the do-while loop is:

do
{
statement;
}while(test-expression);

The braces { } are not necessary when the loop-body contains a single statement. The
following do-while loop prints all upper-case letters :

char ch = 'A' ;
do
{
cout << "\n" << ch ;
ch++;
}while(ch <= 'Z');

The above code prints characters from 'A' onwards until the condition ch <= 'Z' becomes
false.

C++ do-while Loop Example

The most common use of the do-while loop is in menu selection routine, where the menu is
flashed at least once. Then depending upon the user's response it is either repeated or
terminated.

The following example program is a menu selection program. Following program display a
menu regarding rectangle operations and perform according to the user's response:

/* C++ Iteration Statements - C++ do-while Loop */

#include<iostream.h>
#include<conio.h>
#include<math.h>
#include<process.h>
void main()
{
clrscr();
char ch, ch1;
65 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

float l, b, peri, area, diag;


cout<<"Rectangle Menu";
cout<<"\n 1. Area";
cout<<"\n 2. Perimeter";
cout<<"\n 3. Diagonal";
cout<<"\n 4. Exit\n";
cout<<"\nEnter your choice: ";
do
{
cin>>ch;
if(ch == '1' || ch == '2' || ch == '3')
{
cout<<"Enter length & breadth: ";
cin>>l>>b;
}
switch(ch)
{
case '1' : area = l * b ;
cout<<"Area = "<<area;
break ;
case '2' : peri = 2 * (l + b);
cout<<"Perimeter = "<<peri;
break;
case '3' : diag = sqrt((l * l) + (b * b));
cout<<"Diagonal = "<<diag;
break;
case '4' : cout<<"Breaking..Press a key..";
getch();
exit(1);
default : cout<<"Wrong choice !!!!";
cout<<"\nEnter a valid one";
break;
} //end of switch
cout<<"\nWant to enter more (y/n) ? ";
cin>>ch1;
if(ch1 == 'y' || ch1 == 'Y')
cout<<"Again enter choice (1-4): ";
}while(ch1 == 'y' || ch1 == 'Y') ; //end of DO-WHILE loop
getch();
}

66 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

When the above program is compile and executed, it will produce the following output:

C++ Nested Loops


A loop may contain another loop in its body. This form of a loop is called nested loop. But in
a nested loop, the inner loop must terminate before the outer loop. The following is an
example of a nested loop.
/* C++ Iteration Statements - C++ Nested Loops */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i, j;
for(i=0; i<15; i++)
{
for(j=0; j<=i; j++)
{
cout<<"* ";
}
cout<<"\n";
}
getch();
}

When the above program is compile and executed it will produce the following output:

67 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Here is one more program, demonstrating nested loop in C++

/* C++ Loops Program */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num, temp, i, j;
cout<<"Enter a number: ";
cin>>num;
for(i=0; i<10; i++)
{
num++;
temp=num;
for(j=0; j<=i; j++)
{
cout<<num<<" ";
num++;
}
cout<<"\n";
num=temp;
}
getch();
}

68 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Below is the sample run of the above C++ program:

C++ break Statement


In C++, the break statement terminates the loop when it is encountered.
The syntax of the break statement is:

break;

Working of C++ break Statement

Working of break statement in C++

Example 1: break with for loop

// program to print the value of i

69 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
cout << i << endl;
}
return 0;
}
Output
1
2
In the above program, the for loop is used to print the value of i in each iteration. Here,
notice the code:

if (i == 3) {

break;

This means, when i is equal to 3, the break statement terminates the loop. Hence, the output
doesn't include values greater than or equal to 3.

Note: The break statement is usually used with decision-making statements.

Example 2: break with while loop

// program to find the sum of positive numbers

// if the user enters a negative numbers, break ends the loop

// the negative number entered is not added to sum

70 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
// add all positive numbers
sum += number;
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
Output
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: -5
The sum is 6.
In the above program, the user enters a number. The while loop is used to print the total sum
of numbers entered by the user. Here, notice the code,

if(number < 0) {

break;

71 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

This means, when the user enters a negative number, the break statement terminates the loop
and codes outside the loop are executed.

The while loop continues until the user enters a negative number.

break with Nested loop


When break is used with nested loops, break terminates the inner loop. For example,
// using break statement inside
// nested for loop
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// nested for loops
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (i == 2) {
break;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Output
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
72 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
In the above program, the break statement is executed when i == 2. It terminates the inner
loop, and the control flow of the program moves to the outer loop.

Hence, the value of i = 2 is never displayed in the output.

The break statement is also used with the switch statement.

C++ continue Statement


In computer programming, the continue statement is used to skip the current iteration of the
loop and the control of the program goes to the next iteration.
The syntax of the continue statement is:

continue;

Working of C++ continue Statement

Working of continue statement in C++

Example 1: continue with for loop

In a for loop, continue skips the current iteration and the control flow jumps to
the update expression.

// program to print the value of i

73 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// condition to continue
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
1
2
4
5
In the above program, we have used the for loop to print the value of i in each iteration.
Here, notice the code,

if (i == 3) {

continue;

This means

 When i is equal to 3, the continue statement skips the current iteration and starts the
next iteration

 Then, i becomes 4, and the condition is evaluated again.

 Hence, 4 and 5 are printed in the next two iterations.

Note: The continue statement is almost always used with decision-making statements.

74 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Example 2: continue with while loop

In a while loop, continue skips the current iteration and control flow of the program jumps
back to the while condition.

// program to calculate positive numbers till 50 only


// if the user enters a negative number,
// that number is skipped from the calculation
// negative number -> loop terminate
// numbers above 50 -> skip iteration

#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
// continue condition
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated." << endl;
number = 0; // the value of number is made 0 again
continue;
}
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;

75 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

}
Output
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99
In the above program, the user enters a number. The while loop is used to print the total sum
of positive numbers entered by the user, as long as the numbers entered are not greater
than 50.

Notice the use of the continue statement.

if (number > 50){

continue;

 When the user enters a number greater than 50, the continue statement skips the current
iteration. Then the control flow of the program goes to the condition of while loop.

 When the user enters a number less than 0, the loop terminates.

Note: The continue statement works in the same way for the do...while loops.

continue with Nested loop


When continue is used with nested loops, it skips the current iteration of the inner loop. For
example,
// using continue statement inside
// nested for loop
#include <iostream>

76 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

using namespace std;


int main() {
int number;
int sum = 0;
// nested for loops
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
Output
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
In the above program, when the continue statement executes, it skips the current iteration in
the inner loop. And the control of the program moves to the update expression of the inner
loop.

Hence, the value of j = 2 is never displayed in the output.

77 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

C++ Pointers
In C++, pointers are variables that store the memory addresses of other variables.
Address in C++
If we have a variable var in our program, &var will give us its address in the memory. For
example,
Example 1: Printing Variable Addresses in C++
#include <iostream>
using namespace std;
int main()
{
// declare variables
int var1 = 3;
int var2 = 24;
int var3 = 17;
// print address of var1
cout << "Address of var1: "<< &var1 << endl;
// print address of var2
cout << "Address of var2: " << &var2 << endl;
// print address of var3
cout << "Address of var3: " << &var3 << endl;
}
Output
Address of var1: 0x7fff5fbff8ac
Address of var2: 0x7fff5fbff8a8
Address of var3: 0x7fff5fbff8a4
Here, 0x at the beginning represents the address is in the hexadecimal form.
Notice that the first address differs from the second by 4 bytes and the second address
differs from the third by 4 bytes.

This is because the size of an int variable is 4 bytes in a 64-bit system.

78 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Declaration of Pointers

Here is how we can declare pointers.

int *pointVar;

Here, we have declared a pointer pointVar of the int type.


We can also declare pointers in the following way.

int* pointVar; // preferred syntax

Let's take another example of declaring pointers.

int* pointVar, p;

Here, we have declared a pointer pointVar and a normal variable p.


Note: The * operator is used after the data type to declare pointers.

Assigning Addresses to Pointers

Here is how we can assign addresses to pointers:

int* pointVar, var;

var = 5;

// assign address of var to pointVar pointer

pointVar = &var;

Here, 5 is assigned to the variable var. And, the address of var is assigned to
the pointVar pointer with the code pointVar = &var.

79 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Get the Value from the Address Using Pointers

To get the value pointed by a pointer, we use the * operator. For example:
int* pointVar, var;
var = 5;
// assign address of var to pointVar
pointVar = &var;
// access value pointed by pointVar
cout << *pointVar << endl; // Output: 5

In the above code, the address of var is assigned to pointVar. We have used
the *pointVar to get the value stored in that address.
When * is used with pointers, it's called the dereference operator. It operates on a pointer
and gives the value pointed by the address stored in the pointer. That is, *pointVar = var.

Example 2: Working of C++ Pointers


#include <iostream>
using namespace std;
int main() {
int var = 5;
// declare pointer variable
int* pointVar;
// store address of var
pointVar = &var;
// print value of var
cout << "var = " << var << endl;
// print address of var
cout << "Address of var (&var) = " << &var << endl<< endl;
// print pointer pointVar
cout << "pointVar = " << pointVar << endl;

80 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

// print the content of the address pointVar points to


cout << "Content of the address pointed to by pointVar (*pointVar) = " << *pointVar
<<endl;
return 0;
}
Output
var = 5
Address of var (&var) = 0x61ff08
pointVar = 0x61ff08
Content of the address pointed to by pointVar (*pointVar) = 5

Working of C++ pointers

Changing Value Pointed by Pointers

If pointVar points to the address of var, we can change the value of var by
using *pointVar.
For example,
int var = 5;
int* pointVar;
// assign address of var
pointVar = &var;
// change value at address pointVar
*pointVar = 1;
cout << var << endl; // Output: 1
81 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

Here, pointVar and &var have the same address, the value of var will also be changed
when *pointVar is changed.

Example 3: Changing Value Pointed by Pointers


#include <iostream>
using namespace std;
int main() {
int var = 5;
int* pointVar;
// store address of var
pointVar = &var;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
cout << "Changing value of var to 7:" << endl;
// change value of var to 7
var = 7;
// print var
cout << "var = " << var << endl;
// print *pointVar
cout << "*pointVar = " << *pointVar << endl
<< endl;
cout << "Changing value of *pointVar to 16:" << endl;
// change value of var to 16
*pointVar = 16;
// print var
cout << "var = " << var << endl;
// print *pointVar

82 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

cout << "*pointVar = " << *pointVar << endl;


return 0;
}
Output
var = 5
*pointVar = 5
Changing value of var to 7:
var = 7
*pointVar = 7
Changing value of *pointVar to 16:
var = 16
*pointVar = 16

C++ Structures

Structure is a collection of variables of different data types under a single name. It is similar
to a class in that, both holds a collection of data of different data types.
For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, citNo, salary to store
these information separately.
However, in the future, you would want to store information about multiple persons. Now,
you'd need to create different variables for each information per person: name1, citNo1,
salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation
between the variables (information) would exist, it's going to be a daunting task.

A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.
This collection of all related information under a single name Person is a structure.
83 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier (name of the
structure).
Then inside the curly braces, you can declare one or more members (declare variables inside
curly braces) of that structure. For example:

struct Person
{
char name[50];
int age;
float salary;
};

Here a structure person is defined which has three members: name, age and salary.
When a structure is created, no memory is allocated.

The structure definition is only the blueprint for the creating of variables. You can imagine
it as a datatype. When you define an integer as below:

int foo;

The int specifies that, variable foo can hold integer element only. Similarly, structure
definition only specifies that, what property a structure variable holds when it is defined.
How to define a structure variable?

Once you declare a structure person as above. You can define a structure variable as:

Person bill;

Here, a structure variable bill is defined which is of type structure Person.

84 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

When structure variable is defined, only then the required memory is allocated by the
compiler.

Considering you have either 32-bit or 64-bit system, the memory of float is 4 bytes,
memory of int is 4 bytes and memory of char is 1 byte.
Hence, 58 bytes of memory is allocated for structure variable bill.
How to access members of a structure?

The members of structure variable is accessed using a dot (.) operator.


Suppose, you want to access age of structure variable bill and assign it 50 to it. You can
perform this task by using following code below:

bill.age = 50;

Example: C++ Structure


C++ Program to assign data to members of a structure variable and display it.
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
Person p1;
cout << "Enter Full name: ";
cin.get(p1.name, 50);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
85 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

cin >> p1.salary;


cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}

Output

Enter Full name: Magdalena Dankova

Enter age: 27

Enter salary: 1024.4

Displaying Information.

Name: Magdalena Dankova

Age: 27

Salary: 1024.4

Here a structure Person is declared which has three members name, age and salary.
Inside main() function, a structure variable p1 is defined. Then, the user is asked to enter
information and data entered by user is displayed.

C++ Structure and Function

Structure variables can be passed to a function and returned in a similar way as normal
arguments.

86 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Passing structure to function in C++

A structure variable can be passed to a function in similar way as normal argument.


Consider this example:

Example 1: C++ Structure and Function


#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float salary;
};
void displayData(Person); // Function declaration
int main() {
Person p;
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
// Function call with structure variable as an argument
displayData(p);
return 0;
}

void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
87 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

cout << "Salary: " << p.salary;


}

Output
Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name, age and salary of a Person
inside main() function.
Then, the structure variable p is to passed to a function using.

displayData(p);

The return type of displayData() is void and a single argument of type structure Person is
passed.
Then the members of structure p is displayed from this function.

Example 2: Returning structure from function in C++


#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float salary;
};
Person getData(Person);
88 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM
OOPs With C++

void displayData(Person);
int main() {
Person p, temp;
temp = getData(p);
p = temp;
displayData(p);
return 0;
}

Person getData(Person p) {
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
return p;
}

void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}

The output of this program is the same as the program above.

In this program, we have created two structure variables p and temp of type Person under
the main() function.

89 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

The structure variable p is passed to getData() function which takes input from the user
which is then stored in the temp variable.

temp = getData(p);

We then assign the value of temp to p.

p = temp;

Then the structure variable p is passed to displayData() function, which displays the
information.

C++ Pointers to Structure

A pointer variable can be created not only for native types like (int, float, double etc.) but
they can also be created for user defined types like structure.
Here is how you can create pointer for structures:

#include <iostream>
using namespace std;
struct temp {
int i;
float f;
};
int main() {
temp *ptr;
return 0;
}

This program creates a pointer ptr of type structure temp.

90 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

Example: Pointers to Structure


#include <iostream>

using namespace std;

struct Distance {

int feet;

float inch;

};

int main() {

Distance *ptr, d;

ptr = &d;

cout << "Enter feet: ";

cin >> (*ptr).feet;

cout << "Enter inch: ";

cin >> (*ptr).inch;

cout << "Displaying information." << endl;

cout << "Distance = " << (*ptr).feet << " feet " << (*ptr).inch << " inches";

return 0;

Output
Enter feet: 4
Enter inch: 3.5
Displaying information.
Distance = 4 feet 3.5 inches

91 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM


OOPs With C++

In this program, a pointer variable ptr and normal variable d of type structure Distance is
defined.
The address of variable d is stored to pointer variable, that is, ptr is pointing to variable d.
Then, the member function of variable d is accessed using pointer.
Notes:
 Since pointer ptr is pointing to variable d in this program, (*ptr).inch and d.inch are
equivalent. Similarly, (*ptr).feet and d.feet are equivalent.
 However, if we are using pointers, it is far more preferable to access struct members using
the -> operator, since the . operator has a higher precedence than the * operator.

Hence, we enclose *ptr in brackets when using (*ptr).inch. Because of this, it is easier to
make mistakes if both operators are used together in a single code.

ptr->feet is same as (*ptr).feet

ptr->inch is same as (*ptr).inc

92 JAVID AHMAD PARRAY Assistant Professor Computer Science Department, IITM

You might also like