0% found this document useful (0 votes)
16 views

Object Oriented Programming With c++ (Hanumanth Ladwa)

Uploaded by

alejandrokoptez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Object Oriented Programming With c++ (Hanumanth Ladwa)

Uploaded by

alejandrokoptez
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 337

OBJECT ORIENTED

PROGRAMMING WITH
HANUMANTH LADWA

Dedicated to
My parents
And
My sisters
Contents
Chapter Page
Chapter Title
no. no.
1 Introduction to C++ 1 – 25
2 C++ data types 26 – 30
3 I/O Operators 31 – 35
Selection and looping
4 36 – 68
statements
5 Arrays 69 – 80
Built-in and user defined
6 81 – 102
functions
7 Function overloading 103 – 109
8 Function templates 110 - 124
9 Pointers 125 – 137
10 Structures and unions 138 - 154
11 Classes 155 – 174
12 Constructors and destructors 175 – 190
13 Operator overloading 191 - 207
14 Class template 208 – 218
15 Inheritance 219 - 252
Polymorphism and virtual
16 253 – 268
functions
17 File handling 269 - 281

LAB ASSIGNMENTS 282 - 300


CHAPTER 1
INTRODUCTION TO C++
The disadvantages of the previous programming languages leads to evolution
of new programming languages by adding and removing some features of the
currently existing programming languages. This is how the programming
language B has changed to C and now C programming has updated with the
new features and programming technique that makes it increment in its
features and makes it a C++ programming language.
C++ programming language has overcome the disadvantages of C
programming language such as, inability to reuse already existing code, use
of goto statement, global data declaration and limitation on the length of the
code. When there is already one programming language called C present then
what is the necessity to have one more programming language? The answer
for this question is Complexity. C program has limitations such as, when the
programmer crosses more than 50,000 lines of code then it is very difficult
for the programmer himself to debug and locate the error. The C
programming language increases complexity as the program length increases.
In order to reduce the complexity of the program, the programmers
developed a programming language called C++ with the increment in the
features of C programming language.
Programming techniques: A way of writing and accessing the data from the
program is called programming technique or it is a method of how the
program is written and how the program is accessing the data. Mainly there
are two types:
1. Procedural Oriented Programming (POP)
2. Object Oriented Programming (OOP)
Procedural Oriented Programming: it is a way in which the program is
executing sequentially but while executing sequentially the compiler
encounters with the procedure calls. Once the compiler encounters the
procedure call, the control transfers to the procedure and executes all the
statements under the procedure and returns a value back to the main function.
The main function continues to execute the other statements and once again if
the same procedure call or the other procedure call is encountered then the
control again transfers to the procedure and executes all the instructions
present in it and then returns the value back to the calling function (i.e. main
function) as shown in the following figure.

The called procedure may have another procedure call that creates a
hierarchy of procedure calls as shown in the diagram below.
The main program may call procedure 1 but procedure 1 has a call of
procedure 2 and vice versa. Similarly, the main program may call procedure 2
but procedure 2 has a call of procedure 3 and vice versa. Because one
procedure is embedded in another procedure increases complexity and as the
program grows, increases the complexity of the program. It does not model
real world objects.
Object Oriented Programming: programmers developed a new
programming language called Object Oriented Programming (OOP) to
overcome the drawbacks of procedural oriented programming. C++ was
developed by Bjarne Stroustrup at AT & T bell laboratory, New Jersey, USA
in the early 1980. C++ is defined as a superset of C. Earlier C++ was called C
with classes. The name C with classes was renamed as C++ by Rick Mascitti
in 1983. Some of the programming languages that uses OOPs concept are,
C++, VC++, C#, Java, Simula 67 etc.
Let us understand the terminologies used in procedural oriented programming
and object-oriented programming.

Procedural oriented programming Object oriented programming


(POP) (OOP)
Variable Objects
User-defined data types Classes
Structure members Instance variables
Functions Methods
Function call Message passing

Difference between procedural oriented programming and object-


oriented programming.
Procedural oriented programming Object oriented programming
1. Emphasizes on the procedure 1. Emphasizes on the data rather
rather than data. than the procedure.
2. Data is not secured. 2. Data is secured.
3. Uses a top-down approach. 3. Uses bottom-up approach.
4. It does not model real world 4. It models real world entities.
entities.
5. Programs are decomposed into 5. Programs are decomposed into
functions or procedures. objects.

OOP emphasizes on data rather than procedure. Every given problem is


viewed as an object rather than procedure. The ideology here is to unite both
data and functions that operate on data into a single unit called object.
Concepts of OOP:
- Objects
- Class
- Data abstraction
- Data encapsulation
- inheritance
- polymorphism
- dynamic binding
- message passing
Object: Object is an identifiable entity with some characteristics and
behaviour. Object may be a person, place or table of data. Let us take an
example, a mobile cell phone consisting of its features such as color, weight,
price etc. are data whereas a mobile cell phone is used to make an audio or
video call, take photographs, make videos etc are the operations performed
are called functions. Each object is having both of these two features i.e. data
and functions. An object is any real-world entity that has its existence has
both features called data members and operations called function members.
Example, apple, orange, banana etc are the objects of the group called fruit.
Similarly, roses, jasmine, lilies etc are the objects of the group called flowers.
Object: student

Data members
Rollno.
Name
percentage
Function
members
getdata()
putdata()

Class: class is a fundamental building block of object-oriented program


which serves as a blueprint. Class is a user defined data type. Class acts as a
template using which we will be able to create any number of objects of that
type. A class is a collection of similar objects that share common features.
Example: in the above example of objects, the group of fruit is called class.
A group of flowers is called class.
Similarly, the solar system is a class whereas, an individual planet in a solar
system is called an object.
class
Data members
Data1
Data2

Data-n
Function members
Function1
Function2

Function-n

Data abstraction: the act of including only essential details of an entity


without including background details about it is called data abstraction.
Example, let us consider the mobile cell phone with attributes such as, color,
bluetooth, mobile cell phone camera etc. we are not considering how
bluetooth works, or how the camera works or even how the circuit inside the
mobile is designed and what is happening inside. We are interested only in
using the mobile cell phone and its features. Therefore, it is required to know
how to operate a mobile cell phone rather than its internal working, the
internal working is hidden from the user is called abstracted data.
Data encapsulation: the process of wrapping up data and functions into a
single unit called class is called data encapsulation. Data encapsulation makes
data hidden; data hiding is an act of insulating data from outside programs.
The data is not accessible directly to the outside world, except for the
functions defined inside the class definition. These function members provide
an interface between the data and outside world to access the data out of
class.
Inheritance: it is a process of acquiring properties from an object of one
class to properties of an object of another class. The class that inherits the
properties to the other class is called base class or parent class or super class.
The class that inherits the properties from the other class is called derived
class or child class or subclass.
The programmers can add new features to the already existing class without
modifying that class. This is achieved by deriving a new class from the
already existing class. The derived class has its base class features, in
addition to that it has its own features.
Here, the employee is the base class whereas manager, supervisor and clerk
are derived classes. Employee class inherit properties to the derived class and
manager, supervisor and clerk inherited by the base class employee. In
addition to the properties inherited from the base class, derived classes
manager, supervisor and clerk have their own properties.
Polymorphism: it is an ability of the message to process in more than one
form. Poly means many, morph means forms. Polymorphism means many
forms. The best examples for polymorphism are, operator overloading and
function overloading.
The process of making an operator exhibit different behaviors in different
instances is known as operator overloading.
Example: consider an addition operator, when used with numbers, acts as an
arithmetic operator to perform addition. Let’s say, 2+3 gives 5 whereas the
same operator is used with the strings let’s say “Lot”+”us” then it combines
two strings together, it acts as a string concatenation operator which results in
“Lotus”. This different behaviour of the same operator at different instances
is known as operator overloading.
The process of two or more functions having the same name with different
return types or different number of arguments is called function overloading.
Here paint() items are single interface and paint() furniture, paint() vehicle,
paint() building and paint() fabric are many methods.
Example:
int add (int a, int b);
float add (float x, float y) ;
Here, add is a function name which is common in both the functions but
return types of these two functions are different, one is int and another is
float. And the number of arguments is the same in both the functions i.e. 2.
Function overloading is used when we want to perform the same operations
on different data. Function overloading has the same interface but many
methods. You can observe in the above example add is the function name i.e.
interface and many methods means we have addition operations to be
performed on two different data types.
Dynamic binding: binding is the process of providing reference between
more than one module. Dynamic binding means the code associated with a
given procedure call is not known until the time of the call at run-time or at
the time of program execution.
Message passing: message passing is a request for execution of a procedure
for an object. Therefore, a message invokes a procedure in the receiving
object to generate the desired output.
For example, consider an object obj and we have calculated the ‘sum’
(information) by taking add (message) then it is possible to pass message to
this obj object as shown below:
Advantages of OOPs
- Using class and objects, programs are modularized.
- Linking code and object allows related objects to share common code. This
reduces code duplication and code reusability.
- As the data is encapsulated along with functions, the non-member functions
cannot access or modify data. Thus, providing data security.
- Complexity of the program development is reduced through the use of
inheritance.
- Reduces time, as creation and implementation of OOP code is easy.
- Through message passing OOP communicates to the outside system.

Disadvantages of OOPs
- OOP software is not having set standards.
- The adaptability of flow diagrams and object-oriented programming using
classes and objects is a complex process.
- To convert real world problem into an object-oriented model is difficult.
- The classes are overly generalized.

Applications of OOP:
- Computer graphic applications.
- CAD/CAM software.
- Object oriented databases.
- User interface design such as windows.
- Real-time systems.
- Simulation and modelling.
- Artificial intelligence and expert systems.
- Hypermedia, expert text and hypertext.
- Decision support systems and office automation systems.
- Parallel programming and neural networks.

Characteristics of C++:
- Object oriented programming: each problem is viewed as an object
to solve. We mimic the real-world entities into object-oriented
programs to solve the given problems. But it is not possible to convert
the real-world objects into object-oriented programs as it is.
- Portability: it is possible to execute the code written in C++ in any
type of computer and operating system without making any changes.
- Brevity: code written in C++ is short in comparison with other
programming languages.
- Modular programming: C++ uses a modular approach by dividing
the problem into small logical components that performs a specific
task, each module can be written, tested and debugged separately and
linked together while executing. Thus, it saves time.
- C compatibility: C++ is backward compatible with the C language.
Any program written in C can easily be included in a C++ program
without making any change.
- Speed: once the C++ source program is compiled, the compiler
generates an object code present in the .obj file. This code is very
efficient.
- Machine independent: C++ is not dependent on machine hardware
(architecture) or software (operating system).
- Flexibility: C++ is a very versatile and flexible programming
language.
- Wide range of library functions: C++ has a huge collection of built-
in functions that reduces code development time and cost of software
development.
- System software development: As C++ is a middle level language
used for both application software and system software. It helps to
develop systems software such as, operating system, compiler, loader,
macros, assembler etc.
Character set of C++: every programming language has its own set of
characters to form the lexical units. The character set includes letters, digits
and special symbols.
Letters: A – Z (Upper case alphabets) and a – z (Lower case alphabets).
Digits: 0 – 9
Special symbols: , . ?/”{}[]=+-* etc.
C++ programming language is capable of processing any of the 256 ASCII
(American Standard Code for Information Interchange) characters.
Tokens: token is a smallest or basic unit of a program. All the programming
languages are made up of these lexical elements. C++ programming language
has the following tokens.
- Identifiers
- Keywords
- Constants
- Operators
Identifiers: identifier is a name given to the programming elements such as,
arrays, functions and variables. Identifiers can contain letters, digits and
underscore. C is case sensitive, hence uppercase and lowercase letters are
distinct.
Rules for writing identifiers:
- Identifiers must begin with a – z (lowercase letter) or A – Z (uppercase
letter) or _ (underscore).
- Keywords should not be used as an identifier name.
- Uppercase and lowercase letters are different.
For example, marks are different from MARKS.
- No special characters are allowed except _ (underscore).
- The identifier name must be of some reasonable length.
Following are the some of the valid and invalid identifier names,
Valid identifiers: marks, roll_no, _name, student123, etc.
Invalid identifiers:
123name //starts with digit
roll-no //special character hyphen is used
int // keywords are not allowed
keywords: keyword is a predefined word that has fixed meaning to the
compiler that cannot be changed by the programmer. These are the reserved
words that are already defined within the compiler, and the compiler
identifies it as a keyword. All keywords should be written in lowercase letters
only. Some of the keywords are listed below.
if break for do while goto else int
char float double void case const continue
default return unsigned signed short long sizeof
switch typedef union auto volatile enum
Constants:
The quantity or value that does not change during execution of the program is
called constant.
Integer constants: these are the whole numbers without any decimal point.
Integer constants are prefixed with plus or minus sign. Further integer
constants are classified as decimal constants, octal constants, hexadecimal
constants and unsigned constants.
Decimal constants: these are the constants whose base or radix of the
number system is 10. Decimal constants range from 0-9. Any big number can
be generated that consists of a combination of digits between 0 to 9.
Example, 123, -410 etc are decimal constants.
Octal constants: these are the constants whose base or radix of the number
system is 8. Octal constants range from 0-7. Any number generated must
have digits between 0-7 and octal constants always begin with 0.
Example, 0345, -0145
0825 // this integer is an invalid octal number because 8 is not an octal digit
Hexadecimal constants: these are the constants whose base or radix of the
number system is 16. Hexadecimal range from 0 – 9 and a – f or A – F.
hexadecimal digits a (or A) through f (or F) represent value from 10 through
15. Any number generated must be between the range of 0 – 9 and a (or A)
through f (or F) and hexadecimal constants prefixed with 0x or 0X.
Example, 0x8FFFAD, -0X3ADEF etc.
Unsigned constants: to specify an unsigned type we use either u or U suffix.
To specify a long type, we use either l or L suffixes.
Example, 478u; // unsigned constant
0x7777ffL // hexadecimal long type
07524ul //octal unsigned long type
Floating-point constants: these are the constants with the decimal point and
fractional part are called floating point constants. Floating-point constants are
also called real numbers. These constants can be represented in two forms,
- Fractional form
- Mantissa exponent form
Fractional form: fractional form of floating-point numbers can be
represented as integer part followed by decimal point followed by fractional
part.
Example, 20.05
20 . 05
Integer part Decimal point Fractional part
Mantissa exponent notation: any big number or any small number can be
written in the form of power of 10.
Example,
4.523e2 // 4.523 x 102
4.523E-2 // 4.523 x 10-2
-0.4523e-2 // -0.4523 x 10-2
The exponent may be specified using e or E followed by an optional sign (+
or -) and a sequence of digits.
Character constants: a single character enclosed within a pair of single
quotation marks.
For example, ‘a’, ‘@’, ‘&’ etc.
Each of these characters are assigned with the integer constant values called
ASCII (American Standard Code for Information Interchange) values
standardized by ANSI (American National Standard Institute). For example,
ASCII value of A is 65, B is 66 and so on Z is 90 (uppercase letters), a is 97,
b is 98 and so on z is 122 (lowercase letters), 0 is 48, 1 is 49 and so on 9 is 57
(digits).
There is another class of character, which are non-printable, but they have
special meaning. For example, space bar, tab button, enter button, back space
etc. such character constants are called escape sequences. This type of
character constants is always used with the output statements and these types
of constants begin with \ (backslash).
Following table shows the list of escape sequences used in C,
Escape sequence Description
\a system alarm (beep)
\b Backspace
\f Form feed
\n New line (line feed)
\r Carriage return
\t Horizontal tab
\v Vertical tab
\” Double quote
\’ Single quote (apostrophe)
\0 Null character (end of string)
\\ Backslash itself

String constant: a string constant is a sequence of characters enclosed within


a pair of double quotation marks. Strings are sequences of arrays of
characters. By default, the compiler inserts a special symbol called null
character (‘\0’) at the end of the string.
Example, “Computer”, “C++ programming”, “Lotus”, etc.
“Computer” is represented as “Computer\0” in memory.
Operators: an operator is a symbol that tells the compiler what specific
mathematical or logical manipulation has to be performed. Operators in C are
classified as below,
Unary operators: these are the operators that operate only on one operand.
Operator Name
! Logical NOT. It is used to reverse
the state of operand. If a condition is
true then logical NOT return false
value.
& Address-of operator. Returns address
of the operand.
~ One’s complement. Convert 0 to 1
and 1 to 0
* Pointer de-reference. Represent
pointer type.
+ Unary plus. Represent a positive
operand.
++ Increment. Increase the value of an
operand by 1.
- Unary minus. Represent a negative
operand.
-- Decrement. Decrease the value of an
operand by 1.

Increment operator (++): ++ is used to increment the value of the operand


by 1 and the operator can appear before or after the operand. If the operator
prefix operand is called pre-increment operator. If the operator suffix operand
is called post-increment operator. In case of pre-increment, the value of
operand is incremented and then used. In case of post increment, the value of
operand is used then incremented.
Example, if a=5, then a++ returns 5
If a=5, then ++a return 6
Decrement operator (--): -- used to decrement the value of the operand by 1
and the operator can appear before or after the operand. If the operator prefix
operand is called pre-decrement operator. If the operator suffix operand is
called post-decrement operator. In case of pre decrement, the value of
operand is decremented then used. In case of post decrement, the value of
operand is used then incremented.
Example, if a=5, then a--returns 5
If a=5, then --a returns 4
Binary operators: the operator that operates on two operands is called
binary operators. Binary operators are classified as, arithmetic operators,
relational operators, logical operators, bitwise operators and assignment
operators.
Arithmetic operators: the operators supported by C are: + - * / %
Let us consider, a=10 and b=20 then
Operator Description Example
+ Adds two or more a+b returns 30
operands
- Subtract second a-b returns -10
operand from the first
* Multiply first and a*b return 200
second operand
/ Performs integer a/b return 0
division and returns
quotient
% Performs modular a%b return 10
division and returns
remainder

Relational operators:
The relational operators supported by C are: ==, !=, >, >=, <, <=
Let us consider, a=10 and b=20 then:
Operator Description Example
== Compares the values of (a==b) return false
two operands equal or
not
!= Compares the values of (a!=b) return true
two operands equal or
not
> Checks if the value of (a>b) return false
the operand on the left
is greater than the right
operand.
< Checks if the value of (a<b) return true
the operand on the left
is less than the right
operand.
>= Checks if the value of (a>=b) return false
the operand on the left
is greater than or equal
to the right operand.
<= Checks if the value of (a<=b) return true
the operand on the left
is less than or equal to
the right operand.

Logical operators: the logical operators supported by C are: &&, || and !


Let us consider, a=0 and b=10 then:
Operator Description Example
&& Logical AND operator (a&&b) return false
checks if both the
operands are non-zero
then condition becomes
true, otherwise false.
|| Logical OR operator (a||b) return true
checks if both the
operands are zero then
condition becomes
false, otherwise true.
! Logical NOT operator !a return true and !b
reverses the state of the return false
operand. If the operand
is true then it makes it
false and vice versa

Logical AND: the result of the logical AND is true, when both the operands
are true; otherwise the result is false.
Operand1 Operand2 Operand1&&Operand2
False False False
False True False
True False False
True True True

Logical OR: the result of the logical OR is false, when both the operands are
false; otherwise the result is true.
Operand1 Operand2 Operand1||Operand2
False False False
False True True
True False True
True True True
Logical NOT: the result of the logical NOT is true when the operand is
false and vice versa.
Operand !Operand
False True
True False

Bitwise operators: these operators work on bits. The truth table of some of
the bitwise operators is as follows:
a&b (bitwise a|b (bitwise a^b (bitwise
a b
AND) OR) XOR)
0 0 0 0 1
0 1 0 1 0
1 0 0 1 0
1 1 1 1 1
The bitwise operators supported by C++ are listed in the following table:
Operator Description Example
& Binary AND return bit 1 if both operands a&b=0000 1010
bits are 1, otherwise 0.
| Binary OR return bit o if both operands bits a|b=0000 1011
are 0, otherwise 1.
^ Binary eXclusive OR (XOR) returns bit 0 if a^b=0000 1110
there are odd numbers of 1’s. Otherwise 1.
~ Binary negation complements the bits. ~a=0000 0101
Converts bits 1 to 0 and vice versa.
<< Binary left shift operator shifts the number a<<2=0010 1000
of bits specified onto the left.
>> Binary right shift operator shifts the number a>>2=0000 0010
of bits specified onto the right.
Let us consider, a=10 and b=11 then converting into binary,
a=0000 1010 b=0000 1011
The result of bitwise ANDing of a and b is,
a = 0000 1010
b = 0000 1011
a&b = 0000 1010
the result of bitwise ORing of a and b is,
a = 0000 1010
b = 0000 1011
a|b = 0000 1011
the result of bitwise eXclusive-ORing of a and b is,
a = 0000 1010
b = 0000 1011
a^b = 0000 1110
the result of bitwise complement of a is,
a=0000 1010
~a=1111 0101
The left shift bitwise operator changes the content of the operand by shifting
the number of bits specified from left.
General form:
Operand left_shift_operator number_of_bits
Example: a<<2
The result of the bitwise left shift operator is,
Before left shifting of bits
0 0 0 0 1 0 1 0
After two bits shifted to left
0 0 1 0 1 0 0 0

The right shift bitwise operator changes the content of the operand by shifting
the number of bits specified from right.
General form:
Operand right_shift_operator number_of_bits
Example: a>>2
The result of the bitwise right shift operator is,
Before right shifting of bits
0 0 0 0 1 0 1 0
After two bits shifted to right
0 0 0 0 0 0 1 0
Shorthand assignment operators:
Shorthand assignment operators are a compact way of writing assignment
statements in an expression. The shorthand assignment operator works on
both arithmetic operators and bitwise operators.
The general form of a shorthand assignment operator is,
Operand operator=expression
The following table shows the use of assignment operators:
Operator Assignment statements Shorthand assignment
+ (plus) a=a+b a+=b
- (minus) a=a-b a-=b
* (multiplication) a=a*b a*=b
/ (integer division) a=a/b a/=b
% (modular division) a=a%b a%=b
& (bitwise AND) a=a&b a&=b
| (bitwise OR) a=a|b a|=b
^ (bitwise XOR) a=a^b a^=b
<< (bitwise left shift) a=a<<b a<<=b
>> (bitwise right shift) a=a>>b a>>=b

Special operators: the special operators supported by C are listed in the


following table:
Operator Description
sizeof() It returns the number of bytes that each data type
takes.
, Expressions can be separated by comma operator
. (dot) and -> Member access operator used to access each member
(arrow) of class, structure and union.
cast It converts one type of data to another. For example,
int(3.3) would return 3 by truncating a fractional part.
& Ampersand operator returns the address of the
variable
* Asterisk is a pointer operator. It is also called a
dereference operator.

Ternary operator: these are the operators that operate on three or more
operands. The symbol ? is used as a ternary operator. the general form of a
ternary operator is,
Expression ? value1 : value2;
Precedence or hierarchy of operators:
The order in which the expression is evaluated is called precedence of the
operator. It is also called the priority of operators.
For example, 2-3*4 can be evaluate the value -10, not -4 because, the
operator * has high priority than – hence, first 3*4 will be evaluated and then
subtracted from 2. Hence, we get the result of this expression as -10.

The following table shows the priority and associativity of the operators:
Operator category Operators Precedence Associativity
Parentheses, braces (), [] 1 L to R
Unary operators -, ++, --, !, ~, & 2 R to L
Multiplicative operators *, /, % 3 L to R
Additive operators +, - 4 L to R
Shift operators <<, >> 5 L to R
Relational operators <, <=, >, >= 6 L to R
Equality operators ==, != 7 L to R
Bitwise operators &, ^, | 8 L to R
Logical operators &&, || 9 L to R
Conditional operators ?, : 10 R to L
Assignment operators =, +=, -=, *=, /=, 11 R to L
%=, ^=, |=, <<=,
>>=
Comma operator , 12 L to R

Data type conversion: it is a process of converting one type of data into


another type. It is also called type casting.
There are two types of type castings, they are:
- Implicit type conversion
- Explicit type conversion
Implicit type conversion: in implicit conversion, low order data type gets
converted into high order data type automatically by the compiler.
Example, int a=10;
float b=a;
Here, a is of low order data gets automatically converted into higher order
data type. b assigns value 10.0.
explicit type conversion: in explicit type conversion, high order data type
gets converted into low order data type manually by the programmer.
The general form of type casting is,
(data type) variable;
Example, int a=5;
float b;
b=1/a;
b=1/5;
b=0 (result after integer division)
since, b is of float type, the actual value should be 0.2. but it is displaying
result 0. Therefore, to get the actual value, data conversion is required. This
can be achieved by rewriting the statement b=1/a as,
b=1/(float)a;
Structure of a C++ program:
comments or document section
preprocessor directives
definition section
global declaration section
class definition
void main()
{
Declaration section;
Executable statements section;
}
User defined functions
Comments or documentation section: in this section, a textual information
for the other programmer to understand the purpose of the statements or
program can be written either in a single line comment (begins with //) or
multiline comment (/*comment text here*/).
Preprocessor directives: this section begins with # symbol and #include is a
preprocessor directive. These are the statements that tells the compiler to
include header files such as, #include<stdio.h>, #include<conio.h>,
#include<math.h> etc.
Definition section: in this section, we define constants, expressions,
structures, functions, classes, objects etc. this section is optional to use. This
section begins with #define. For example, if you are calculating area of a
circle, then the formula to calculate area of circle is 3.142*r*r. here, instead
of writing the constant value 3.142, we can define it in the definition section
as, #define PI 3.142 whenever the compiler encounters the symbol PI it
replaces PI with the value 3.142. writing variable names in capital letters (PI
as in the example) is a good programming practice.
Global declaration section: the variables declared in this section are
accessible throughout the program and even in the functions. Variables
declared in this section expands its scope. This section is optional, and this
section can be used whenever there is need in the program.
Class definition: class is a user defined data type that serves as a template for
objects that undergo operation. Details about class definition will be
discussed in the forthcoming chapters.
main() function: every C++ program starts executing from main() function.
Without the main() function no C++ program executes. The main() function
should not be terminated by a semicolon. Each C++ program must have at
least and at most one main() function.
Braces { }: the curly open brace indicates that it is the beginning of the
main() function and curly close brace indicates that it is the termination of the
main() function. Curly opening and closing braces are also used in functions
and compound statements.
Declaration section: all the variables are declared in the declaration section
before using them in the program. This helps the compiler to allocate
memory space for the variables in a computer memory. The variables
declared in a particular block of code has its scope within that block.
Executable statements section: the executable statements could be,
expressions, input-output functions, conditional statements, looping
statements, etc.
User defined functions: these are the finite set of instructions written by the
user that performs a specific operation, hence the name user defined
functions. User defined functions are also called subprograms or subroutines.
A sample C++ program
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<“Welcome to the world of C++”;
getch();
}
Output:
Welcome to the world of C++
The first line tells the compiler to include an input/output stream header file
that consists of cin and cout objects to perform input and output operations.
The second header file console input and output consists of a getch() function
used to keep the output of the program intact on the console till the user
presses any button. The third statement is void main() function, here, void is
one of the data types which specifies nothing. If we do not write void
explicitly then, the main() function returns integer type of data by default.
Curly open brace indicates the beginning of the body of the main() function.
cout is used to display a line of text written in it i.e. Welcome to the world of
C++. getch() is a built-in function present in a conio.h header file. Curly
closing brace indicates that this is the termination point of the main()
function.
Library functions: C++ provides a set of built-in functions that reduces the
burden of the programmer by reducing the length of the code. Built-in
functions are ready made functions that perform a specific task and these are
already present in the compiler in the form of different header files, such as,
math.h is used for mathematical functions, ctype.h is used for character
functions, string.h is used for string manipulation functions. Etc. let us study
each one of them with examples,
Mathematical functions:
Function Meaning
sin(x) Sine of an angle x
cos(x) Cosine of an angle x
exp(x) Exponential function of x
log(x) Logarithm of x
log10(x) Logarithm of number x to the base
10
sqrt(x) Square root of x
pow(x,y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of floating-point x

Character functions: all the character functions are present in the ctype.h
header file. The following table shows some of the functions present in the
ctype.h header file.
Function Meaning
isalpha(c) It returns true if c is an alphabet,
otherwise false.
isdigit(c) It returns true if c is a digit,
otherwise false.
isalnum(c) It returns true if c is alphabet or
digit, otherwise false.
islower(c) It returns true if c is lowercase letter,
otherwise false
isupper(c) It returns true if c is uppercase letter,
otherwise false
toupper(c) It converts lowercase letters to
uppercase letters.
tolower(c) It converts uppercase letters to
lowercase letters.
String functions: the string manipulation functions are present in a string.h
header file. Some of the functions are listed in the table below.
Function Meaning
strlen(s) It returns the number of characters
present in the string including blank
spaces.
strcat(s1,s2) This function combines or
concatenates two strings together.
String 2 concatenates at the end of
string 1.
strcpy(s1,s2) It copies the string 2 to string 1
strcmp(s1,s2)==0 It compares s1 and s2 and finds out
strcmp(s1,s2)>0 whether s1 equal to s2, s1 greater
strcmp(s1,s2)<0 than s2 or s1 less than s2
strcmpi(s1,s2)==0 It compares s1 and s2 ignoring case
strcmpi(s1,s2)>0 and finds out whether s1 equal to s2,
strcmpi(s1,s2)<0 s1 greater than s2 or s1 less than s2
strrev(s) It reverses a string
strupr(s) It converts string into upper case
strlwr(s) It converts string into lower case

Console I/O functions: some of the functions present in the conio.h header
file are listed in the table below.
Function Meaning
getch() It is used to retain the output on the
console till the user presses any
button.
getche() It is used to retain the output on the
console till the user presses any
button the value of the character
returned from getche().

EXERCISES
1. Explain the programming techniques.
2. What are the terminologies used in procedure-oriented
programming and object-oriented programming?
3. What is the difference between procedure-oriented programming
and object-oriented programming?
4. Briefly explain the concepts of OOP.
5. Write the advantages of OOP.
6. Describe the disadvantages of OOP.
7. Mention the applications of OOP.
8. What are the characteristics of C++?
9. Mention the character set of C++.
10. What is a token? Mention the types of tokens.
11. What is an identifier? State the rules for declaring identifiers.
12. Define keywords with examples.
13. What are constants? Mention its types.
14. Define character constant. Give an example.
15. What is string constant? Mention an example.
16. What are operators? Explain with examples.
17. Explain increment and decrement operators with an example.
18. What are arithmetic operators? Explain with examples.
19. What are relational operators? Explain with examples.
20. Describe the logical operators with an example for each.
21. Explain bitwise operators with examples.
22. What are ternary operators? Explain with an example.
23. What is the hierarchy of operators? Explain with an example.
24. Describe type conversion. Name its types.
25. Explain the structure of C++ program.
26. Name some header files used in C++.
27. Explain any five character functions with examples.
28. Describe any five string functions with examples.
29. Explain I/O functions.
CHAPTER 2
C++ DATA TYPES
Introduction: C++ provides a rich set of data types to handle the data used
by the program. It is categorized as, primitive data types, derived data types
and user defined data types. Data types indicate the type of data that the
variable can hold.
Variables: a variable is a quantity that changes during execution of the
program. C++ encourages us to use meaningful names for variables.
Variables are declared in the declaration section before using them in the
program. In C++ program, the variable represents the memory location that
holds the value assigned to it.
Declaration of a variable: the syntax for declaring a variable is,
Data_type variable_name;
Here, the variable_name is the identifier name that must satisfy all the rules
for declaring an identifier. The variables are named storage locations whose
values can be manipulated during program execution.
Some valid variables:
Roll_no data date_of_birth percentage
Some invalid variables:
float //it is a keyword
total_% //special symbol % is not allowed
2subjects //started with the digit
My result //blank space is not allowed
Initializing a variable:
The general form of initializing a variable is,
Data_type variable_name=value;
Example: int a=10;
Here, int is one of the primitive data types. And a is a variable that holds
integer type of data. The variable a is a named storage location. 10 is a
constant value assigned to the variable a of type integer. A semicolon
indicates termination of variable declaration.
How to make a value of the variable constant?
Example, int a=10;
In this example, the variable a is of type integer with value 10 is assigned to it
can be changed at any point of time. In order to make it constant we use a
keyword const before the data types as follows:
const int a=10;
now, the value of the variable a is constant, that cannot be changed during the
program execution.

Classification of data types: data types are classified as follows.


Fundamental data types: these data types are also called as primitive data
types or basic data types or primary data types or simple data types or built-in
data types.
Fundamental data types include: int, char, float, double and void.
i) int: integers are whole numbers without decimal point and
fractional part. Integer numbers can be both positive and negative.
Integer numbers occupy 2 bytes of memory. The range of integers
depends on the word length of the computer. Word length means the
number of bits that the CPU can process at a time. If the computer is
an 8 bit, then the range of int is,
-28-1 to +28-1-1 that is,
-128 to +127
If the integer numbers are unsigned then, it ranges from 0 to 256.
If the computer is of 16 bits, then the range of int would be,
-216-1 to +216-1-1 that is,
-32768 to +32767
If the integer numbers are unsigned then, it ranges from 0 to 65535.
Valid integers: -120, 1500, 32000, +19000, 0 etc.
Invalid integers: 13,300 //comma is not allowed
-130.5 //decimal point is not allowed
56,000.30 //comma and decimal number is not allowed
40000 //out of integer range
ii) char: a single character enclosed within a pair of single quotation
marks is character constant. Characters could be a single letter, a
single digit, a single special symbol enclosed within a pair of single
quotation marks. Example, ‘a’, ‘5’, ‘#’ etc. a char type takes 1 byte
of data in memory. These characters represent a unique number
called ASCII codes. The range of characters is, -128 to +127. If the
characters are unsigned then, it is ranging from 0 to 255.
iii) float: these are the numbers with the fractional part. Floating-point
numbers can be both positive and negative. Example, -85.25, 0.0,
33.20, etc. the range of floating-point numbers is, -3.4e-38 to
+3.4e+38. Floating point numbers will occupy 4 bytes of memory.
iv) double: these are also the floating-point numbers with the higher
precision than float type of data. The data type double will give a
more accurate value up to 16 digits after the decimal point, whereas,
float will give an approximate value up to 6 digits after the decimal
point. This type of data takes 8 bytes of memory. The range of
double types of data is, -1.7e-308 to +1.7e+308.
v) void: this data type specifies nothing. It is normally used with
functions where the function has nothing to return back to the
calling function.
Modifiers: a modifier is used to alter the meaning of the data type. in order to
make the data types more precise and fit as per our requirements. These
modifiers are also called qualifiers.
Types of modifiers are listed here.
- signed
- unsigned
- long
- short
The modifiers signed, unsigned, long and short can be applied to integer type.
Signed and unsigned can be applied to char and long can be applied to
double. The modifiers signed and unsigned can also be used as prefixes to
long or short modifiers.
Following table shows the data types and their range.
Type Size in bytes Range
char 1 -128 to +127
unsigned char 1 0 to 255
signed char 1 -128 to +127
int 2 -32768 to +32767
unsigned int 2 0 to 65535
signed int 2 -32768 to +32767
short int 2 -32768 to +32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to +32767
long int 4 -2147483648 to 2147483647
signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 -3.4e-38 to +3.4e+38
double 8 -1.7e-308 to +1.7e308
long double 10 -3.4e-4932 to 1.1e+4932

Derived data types: derived data types are created using fundamental data
types. They include arrays, functions, pointers and references. The details
about these concepts will be covered in the forthcoming chapters.
User defined data types: user defined data types are also constructed using
fundamental data types. They include structure, union, class and enumeration.
Now we will learn enumerated types of data. We will learn in detail about
structure, union and class in later chapters.
Enumerated data type: it is an user defined data type consisting of a set of
named constants called enumerators. enum is a keyword that assigns values
0, 1, 2, … automatically.
The general form of enum is as follows:
enum[tag]{enum-list};
Example 1: enum ratings{very_bad,bad,good,better,best}; // definition of
enum type
ratings myrate; //declaration of variable of type ratings
example 2: enum rays{alpha,beta,gamma};
Here in this example, alpha takes value 0, beta takes value 1 and gamma
takes value 2.
We can also change the default values to any user defined values.
Example 3: enum shirtsize{small=10, medium=20,large=30};
Here in this example small takes value 10, medium takes value 20 and large
takes value 30.

EXERCISES
1. What are data types? Classify them.
2. Describe a variable with its declaration and initialization.
3. Explain basic data types with an example for each.
4. What are modifiers? Mention its types.
5. Explain enumerated data type with an example.
CHAPTER 3
I/O OPERATORS
Introduction: Program written in C, takes one or more input data and output
information. There are two methods of writing programs, one is a non-
interactive way where variables are initialized. Another is an interactive way
where the program will interact with the user to enter some data through the
keyboard. Inputting data is done through keyboard and the processed data i.e.
information will be displayed on to the monitor.
The input output operation can be performed by using the objects cin and
cout present in iostream.h class. Using these two objects, we will be able to
interact with the user by printing messages on the screen and getting input
from the user through the keyboard.
C++ uses the data input and output in the form of stream. That is, a stream is
a flow of bytes from input device to output device and vice-versa.
Input operator “>>”

Input in C++ is done by using stream extraction (>>) on the cin stream. The
operator must be followed by the variable that will store the data that is going
to be extracted from the stream.
Ex: int regno;
cin>>regno;
The first statement in example declares the variable of type int called regno,
and the second one waits for an input from cin in order to store it in this
integer variable. cin stands for console input.
Output operator “<<”

Outputting in C++ is done by using stream insertion (<<) on the cout stream.
cout stands for console output.
Ex: cout<<”Let us learn C++ programming”;
Notice that the sentence in the instruction is enclosed between double quotes
(“), because it is a string constant.
// Write a program to find the sum of 2 numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int x,y,sum;
clrscr();
cout<<"Enter two numbers:\n";
cin>>x>>y;
sum=x+y;
cout<<"The sum of "<<x<<" and "<<y<<" = " <<sum;
getch();
}
Output:
Enter two numbers:
3
2
The sum of 3 and 2 = 5
I/O Cascading:
C++ supports the use of stream extraction (>>) and stream insertion (<<)
operators many times in a single input (cin) and output (cout) statements. If a
program requires more than one input variable then it is possible to input
these variables in a single cin statement using multiple stream extraction
operators. Similarly, when we want to output more than one result then this
can be done using a single cout statement with multiple stream insertion
operators. This is called the cascading of input output operators.
Ex: cout<<”enter the value of x”;
cin>>x;
cout<<”enter the value of y”;
cin>>y;
instead of using cin statement twice, we can use a single cin statement and
input the values for the two variables x and y using multiple stream extraction
operator as shown below,
cout<<”enter the value for x and y”;
cin>>x>>y;
similarly, we can even output multiple results in a single cout statement using
cascading of stream insertion operator as shown below,
cout<<”the sum of ”<<x<<” and ” <<y<<” = “ <<x+y;
// Write a program to create simple calculator
#include<iostream.h>
#include<conio.h>
void main()
{
int a, b, sum, diff, prod, quot, rem;
cout<<"Enter two numbers:\n";
cin>>a>>b;
sum=a+b;
diff=a-b;
prod=a*b;
quot=a/b;
rem=a%b;
cout<<"Sum="<<sum<<"\nDifference="<<diff<<"\nProduct="
<<prod<<"\nQuotient="<<quot<<"\nRemainder="<<rem;
getch();
}
Output:

Enter two numbers:


5
10
Sum=15
Difference=-5
Product=50
Quotient=0
Remainder=5
//Write a program to convert seconds into hours, minutes and seconds
#include<iostream.h>
#include<conio.h>
void main()
{
int totalseconds, minutes, seconds, hours;
clrscr();
cout<<"Enter the total seconds: ";
cin>>seconds;
totalseconds=seconds;
hours=seconds/3600;
seconds=seconds%3600;
minutes=seconds/60;
seconds=seconds%60;
cout<<totalseconds<<" seconds= "<<hours<<" hours-"<<minutes<<"
minutes-"<<seconds<<" seconds";
getch();
}
Output:
Enter the total seconds: 3661
3661 seconds= 1 hours-1 minutes-1 seconds

EXERCISES
1. What are the input and output operators? Explain with a neat
diagram.
2. What is an input output cascading? Explain an example.
3. Write a program to find the sum of two numbers.
4. Write a program to create a simple calculator.
5. Write a program to convert seconds into hours, minutes and
seconds.
6. Write a program to compute simple interest.
7. Write a program to calculate compound interest.
8. Write a program to find the area of a cube, cuboid, cylinder.
9. Write a program to convert Fahrenheit temperature into Celsius.
10. Write a program to find the volume of a square, cone, rectangle.
CHAPTER 4
SELECTION AND LOOPING
STATEMENTS
Introduction: in general, instructions written are executed in a linear fashion
called sequential order. It is not mandatory that all the instructions are to be
executed in the order in which they are written, in some situations, the control
may bifurcate based on the condition, some statements get executed
repeatedly a certain number of times based on the condition. Some statements
may jump from one statement to another based on the condition imposed.
C++ provides two types of control statements:
- selection statements
- iterative statements
Selection statements: Selection statements are also called conditional control
statements used to check the condition, based on the condition, the control
makes decision and branching.
There are four types of selections statements,
i. if-statement
ii. if-else statement
iii. nested statement
iv. switch statement
if statement: if statement is also called a one-way branching statement. In
simple if statements, if the condition is true then the statement or set of
statements will get executed. If the condition is false then the next statements,
if any, will get executed.
The general form of if statement is,
if(condition) OR if(condition)
statement1; {
statement1;
statement2;

statement-n
}
// Write a program to display the class obtained by the student
#include<iostream.h>
#include<conio.h>
void main()
{
float percentage;
clrscr();
cout<<"Enter the percentage: ";
cin>>percentage;
if(percentage>35)
cout<<"PASS";
getch();
}
Output:
Enter the percentage: 62
PASS

// write a program to find largest of two numbers using if statement


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,large;
clrscr();
cout<<"Enter two numbers\n";
cin>>a>>b;
large=a;
if(b>large)
large=b;
cout<<"Largest number is "<<large;
getch();
}
Output:
Enter two numbers
14
51
Largest number is 51

// Write a program to check whether the number is positive or negative


#include<iostream.h>
#include<conio.h>
void main()
{
int n;
clrscr();
cout<<"Enter the number: ";
cin>>n;
if(n>=0)
cout<<"The number "<<n <<" is positive";
getch();
}
Output:

Enter the number: 6


The number 6 is positive

if-else statement: if-else statement is also called two-way branching. In an if-


else statement the condition will be checked, if the condition is true then
statement 1 will get executed. Otherwise, else part i.e. statement 2 will get
executed.
The general form of if-else statement is,
if(condition)
statement 1;
else
statement 2;
// Write a program to check the eligibility of a person for voting
#include<iostream.h>
#include<conio.h>
void main()
{
int age;
clrscr();
cout<<"Enter the age of a person: ";
cin>>age;
if(age>=18)
cout<<"You are eligible for voting";
else
cout<<"You are not eligible for voting";
getch();
}
Output:
run 1:
Enter the age of a person: 21
You are eligible for voting

run 2:
Enter the age of a person: 17
You are not eligible for voting

// Write a program to find the even or odd number


#include<iostream.h>
#include<conio.h>
void main()
{
int n;
clrscr();
cout<<"Enter the number: ";
cin>>n;
if(n%2==0)
cout<<"The number "<<n<<" is even";
else
cout<<"The number "<<n<<" is odd";
getch();
}
Output:

run 1:
Enter the number: 5
The number 5 is odd

run 2:
Enter the number: 10
The number 10 is even

Nested if statement: one if statement is enclosed within another if statement


such if statements are called nested if statement. There are two formats.
Format I: if-else-if statement: this statement is also called an if-else-if
ladder. There are several alternatives available, out of which we have to
choose the statement that matches with the condition. It is also called
multiway branching.
The general form of if-else-if statement is,
if(condition1)
statement1;
else
if(condition2)
statement2;
else
----
else
if(condition-n)
statement-n;
else
default statement;
First condition 1 is tested. If the condition is true then statement 1 is
executed. Otherwise, condition 2 is tested. If condition 2 is true then
statement 2 is executed. Otherwise, condition 3 is tested and so on. Finally,
condition-n is tested. If it is true, statement-n is executed. If none of the
conditions is true then the default statement is executed.
// write a program to find class obtained by the student
#include<iostream.h>
#include<conio.h>
void main()
{
float percentage;
clrscr();
cout<<"Enter the percentage: ";
cin>>percentage;
if(percentage>=85.0&&percentage<=100.0)
cout<<"Distinction";
else
if(percentage>=60.0)
cout<<"First class";
else
if(percentage>=50.0)
cout<<"Second class";
else
if(percentage>=35.0)
cout<<"Pass class";
else
cout<<"Fail";
getch();
}
Output:
run 1:
Enter the percentage: 92
Distinction

run 2:
Enter the percentage: 80
First class

run 3:
Enter the percentage: 55
Second class

run 4:
Enter the percentage: 42
Pass class

run 5:
Enter the percentage: 33
Fail

// Write a program to display rainbow color


#include<iostream.h>
#include<conio.h>
void main()
{
int color_code;
clrscr();
cout<<"Rainbow colors:\n1. Violet\n2. Indigo\n3. Blue\n4. Green\n5.
Yellow\n6. Orange\n7. Red\n";
cout<<"\nEnter your choice (select number between 1 to 7): ";
cin>>color_code;
if(color_code==1)
cout<<"You have chosen Violet";
else if(color_code==2)
cout<<"You have chosen Indigo";
else if(color_code==3)
cout<<"You have chosen Blue";
else if(color_code==4)
cout<<"You have chosen Green";
else if(color_code==5)
cout<<"You have chosen Yellow";
else if(color_code==6)
cout<<"You have chosen Orange";
else if(color_code==7)
cout<<"You have chosen Red";
else
cout<<"Chosen wrong color code";
getch();
}
Output:

run 1:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 1


You have chosen Violet

run 2:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 2


You have chosen Indigo

run 3:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 3


You have chosen Blue

run 4:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 4


You have chosen Green

run 5:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 5


You have chosen Yellow

run 6:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 6


You have chosen Orange

run 7:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 7


You have chosen Red

run 8:
Rainbow colors:
1. Violet
2. Indigo
3. Blue
4. Green
5. Yellow
6. Orange
7. Red

Enter your choice (select number between 1 to 7): 8


Chosen wrong color code
Format II: If-else-if statement: it contains an if-else statement within
another if-else statement.

The general form of if-else-if statement is,


if(condition1)
if(condition2)
statement1;
else
statement2
else
if(condition3)
statement3;
else
statement4;
if condition 1 is true and condition 2 is also true then statement 1 will get
executed. If condition 1 is true and condition 2 is false then statement 2 will
get executed. If the condition 1 is false then the control transfers to the else if
part and checks the condition 3, if condition 3 is true then statement 3 will get
executed otherwise statement 4 will get executed.
// Write a program to find the greatest of three numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
cout<<"Enter three numbers\n";
cin>>a>>b>>c;
if(a>b)
if(a>c)
cout<<a <<" is the greatest";
else
cout<<c<<" is the greatest";
else if(b>c)
cout<<b<<" is the greatest";
else
cout<<c<<" is the greatest";
getch();
}
Output:
Enter three numbers
3
1
2
3 is the greatest

// Write a program to find the eligibility for marriage


#include<iostream.h>
#include<conio.h>
void main()
{
char gender;
int age;
clrscr();
cout<<"Enter the gender (M/F): ";
cin>>gender;
cout<<"Enter the age: ";
cin>>age;
if(gender=='m'||gender=='M')
if(age>=21)
cout<<"You are eligible to marry";
else
cout<<"You are not eligible to marry";
else if(gender=='f'||gender=='F')
if(age>=18)
cout<<"You are eligible to marry";
else
cout<<"You are not eligible to marry";
getch();
}
Output:

run 1:
Enter the gender (M/F): m
Enter the age: 38
You are eligible to marry

run 2:
Enter the gender (M/F): m
Enter the age: 20
You are not eligible to marry

run 3:
Enter the gender (M/F): f
Enter the age: 18
You are eligible to marry

run 4:
Enter the gender (M/F): f
Enter the age: 17
You are not eligible to marry
switch statement: it is an alternative of if-else-if ladder. It is used to select
one block of code if the expression present in the switch statement matches
with the case label. Here switch expression will hold only one of the three
values, int, char or Boolean values. This statement provides multiple way
branching.
The general form of switch statement is,
switch(expression)
{
case label-1: statement 1;
break;
case label-2: statement 2;
break;

case label-n: statement n;
break;
default: default-statement;
}
The break statement is used to indicate that the case label is terminated. The
default statement will get executed if the switch expression does not match
with any case label.

// Write a program to display week day


#include<iostream.h>
#include<conio.h>
void main()
{
enum week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum week day;
int dayno;
clrscr();
day=Fri;
switch(day)
{
case 0:cout<<"Today is Sunday";
break;
case 1:cout<<"Today is Monday";
break;
case 2:cout<<"Today is Tuesday";
break;
case 3:cout<<"Today is Wednesday";
break;
case 4:cout<<"Today is Thursday";
break;
case 5:cout<<"Today is Friday";
break;
case 6:cout<<"Today is Saturday";
break;
default:cout<<"Wrong day number";
break;
}
getch();
}
Output:
Today is Friday

// Write a program to perform arithmetic calculations


#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,sum,diff,mul,quot,rem;
int choice;
clrscr();
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"OPERATIONS:\n1. Addition\n2. Subtraction\n3. Multiplication\n4.
Division\n5. Modulus\n\nChoose the operation: ";
cin>>choice;
switch(choice)
{
case 1: sum=a+b;
cout<<a<<"+"<<b<<"="<<sum;
break;
case 2: diff=a-b;
cout<<a<<"-"<<b<<"="<<diff;
break;
case 3: mul=a*b;
cout<<a<<"*"<<b<<"="<<mul;
break;
case 4: quot=a/b;
cout<<a<<"/"<<b<<"="<<quot;
break;
case 5: rem=fmod(a,b);
cout<<a<<"%"<<b<<"="<<rem;
break;
default:cout<<"Error in selection";
break;
}
getch();
}
/*Output

run 1:
Enter two numbers:
2
3
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 1


2+3=5
run 2:
Enter two numbers:
6
5
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 2


6-5=1

run 3:
Enter two numbers:
3
5
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 3


3*5=15
run 4:
Enter two numbers:
7
2
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 4


7/2=3.5

run 5:
Enter two numbers:
5
6
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 5


5%6=5

run 6:
Enter two numbers:
4
5
OPERATIONS:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Modulus

Choose the operation: 6


Error in selection
Iterative statements: iterative statements that allow repeated execution of a
set of instructions till a certain condition is satisfied. Iterative statements are
also called looping statements. There are three types of looping statements.
- while loop
- do-while loop
- for loop
while loop: it is also called a pretested looping structure, because the
condition is checked before repeated execution of a set of statements.
General form,
while(condition) OR while(condition)
statement; {
statement 1;
statement 2;

statement n;
}
// Write a program to find the sum of first n natural numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int n,sum=0,i=1;
clrscr();
cout<<"Enter the number: ";
cin>>n;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<<"Sum="<<sum;
getch();
}
Output:
Enter the number: 10
Sum=55
// Write a program to count the frequency of each vowel in the string.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[50];
int ac=0,ec=0,ic=0,oc=0,uc=0,i=0;
clrscr();
cout<<"Enter the string: ";
cin>>str;
int l=strlen(str);
while(i<=l)
{
switch(str[i])
{
case 'a':
case 'A': ac++;
break;
case 'e':
case 'E': ec++;
break;
case 'i':
case 'I': ic++;
break;
case 'o':
case 'O': oc++;
break;
case 'u':
case 'U': uc++;
break;
}
i++;
}
cout<<"a or A appeared "<<ac<<" times"<<endl;
cout<<"e or E appeared "<<ec<<" times"<<endl;
cout<<"i or I appeared "<<ic<<" times"<<endl;
cout<<"o or O appeared "<<oc<<" times"<<endl;
cout<<"u or U appeared "<<uc<<" times"<<endl;
getch();
}
Output:
Enter the string: Hanumanth
a or A appeared 2 times
e or E appeared 0 times
i or I appeared 0 times
o or O appeared 0 times
u or U appeared 1 times

do-while loop: in this looping structure the condition will be checked


executing a set of instructions at least once, hence it is also called a post-
tested looping structure.

General form of do-while loop is,


do do
{ {
Statement1; OR statement 1;
}while(condition); statement 2;

Statement n;
}while(condition);
// Write a program to find the sum of even and odd n natural numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int n, i=1, esum=0, osum=0;
clrscr();
cout<<"Enter the number: ";
cin>>n;
do
{
if(i%2==0)
esum+=i;
else
osum+=i;
i++;
}while(i<=n);
cout<<"Sum of even numbers from 1 to "<<n<<"="<<esum<<endl;
cout<<"Sum of odd numbers from 1 to "<<n<<"="<<osum;
getch();
}
Output:
Enter the number: 5
Sum of even numbers from 1 to 5=6
Sum of odd numbers from 1 to 5=9
for loop: this looping statement is used when there are a fixed number of
iterations. When we know in advance exactly how many times a set of
statements should be repeatedly executed.
The general form of for loop is,
for(initialization; condition; increment/decrement)
{
Statement1;
Statement2;

Statement-n;
}
// write a program to print first 5 natural even numbers
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=2;i<=10;i=i+2)
cout<<i<<",";
cout<<"\b.";
getch();
}
Output:
2,4,6,8,10.
/* Write a program to count the number of alphabets, digits and special
symbols present in a string. */
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char name[20];
int i,alpha=0,digit=0,special=0,l;
clrscr();
cout<<"Enter your name: ";
cin>>name;
l=strlen(name);
for(i=0;i<l;i++)
{
if((name[i]>='a'&&name[i]<='z')||(name[i]>='A'&&name[i]<='Z'))
alpha++;
else if(name[i]>='0'&&name[i]<='9')
digit++;
else
special++;
}
cout<<"Your name "<<name<<" contains\n";
cout<<alpha<<" Alphabets"<<endl;
cout<<digit<<" Digits"<<endl;
cout<<special<<" Special symbols"<<endl;
getch();
}
Output:
Enter your name: Hanumanth@123
Your name Hanumanth@123 contains
9 Alphabets
3 Digits
1 Special symbols
Jump statements: jump statements are used to terminate or exit or transfer
the control out of the loop, this can be done by using break, exit and
continue statements.
break statement: break statement can be used in two ways; one we have
already used in switch statements to transfer the control out of switch
statements. Another is, used to terminate the loop.
General form of break statement is,
break;
/* write a program to check whether a given number is prime or not
using break statement*/
#include<iostream.h>
#include<conio.h>
void main()
{
int i,n,status=1;
clrscr();
cout<<"Enter the number: ";
cin>>n;
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
status=0;
cout<<"It is not a prime number";
break;
}
}
if(status)
cout<<"It is a prime number";
getch();
}
Output:

run 1:
Enter the number: 3
It is a prime number

run 2:
Enter the number: 6
It is not a prime number
exit() function: break statement was used to exit out of the looping and
switch statements, but exit() function, present in the stdlib.h header file is
used to terminate the entire program.
The general form of exit() function is,
exit();
/* write a program to check whether a given number is prime or not
using exit() function */
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n,i;
clrscr();
cout<<"Enter the number: ";
cin>>n;
for(i=2;i<=n/2;++i)
if(n%i==0)
{
cout<<"It is not a prime number";
exit(0);
}
cout<<"It is a prime number";
getch();
}
Output:

Enter the number: 7


It is a prime number
continue statement: continue statement is used to skip the part of a looping
statement and does not terminate the loop.
The general form of continue statement is,
continue;
// write a program to demonstrate the use of continue statement
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=10;i>0;i--)
{
if(i==5)
continue;
cout<<i<<",";
}
cout<<"\b.";
getch();
}
Output:
10,9,8,7,6,4,3,2,1.
goto statement: goto statement transfers the control from one point to
another. The destination point is identified by a label followed by a colon (:).
The general form of goto statement is,

goto ENDING; BEGINNING:


------ ------
------ OR ------
ENDING; ------
------ goto BEGINNING;
In the first syntax, the label ENDING is placed after the goto ENDING
statement. The statements immediately after the goto will be skipped,
whereas the control jumping to the label ENDING. This type of jumping is
called forward jumping. Whereas, in the second syntax, the label
BEGINNING is placed before the goto statement. This type of jump is
known as backward jump and it will form a loop.
// write a program to print numbers from 1 to 10 using goto statement
#include<iostream.h>
#include<conio.h>
void main()
{
int n=1;
clrscr();
loop:cout<<n<<",";
n++;
if(n<=10)
goto loop;
cout<<"\b.";
getch();
}
Output:
1,2,3,4,5,6,7,8,9,10.
EXERCISES
1. What are selection and iterative statements?
2. Explain a simple if statement with an example.
3. Describe an if-else statement with a programming example.
4. Explain working of switch statements with an example.
5. Briefly explain the while loop with general form, flowchart and an
example.
6. Explain working of do-while looping construct with an example.
7. Differentiate between while and do-while loop.
8. Write a program to find the sum of the series 1+x+x2+…+xn using
for loop.
9. Write a program to find the GCD and LCM of numbers.
10. Explain for loop with general form, flowchart and an example.
11. Write a program to find the sum of the series 1+1/3!+1/5!+…+1/n!
using a while loop.
12. Write a program to find the factorial of a number using a for loop.
13. Write a program to find the sum of digits of a given number.
14. Explain jump statements with an example for each.
15. Write a program to print numbers from 1 to 10 using goto
statement
16. Write a program to print numbers from 10 to 1 using goto
statement
CHAPTER 5
ARRAYS
Introduction: till now, we have seen different types of variables that hold
only one value, but in some situations, we require to process more than one
data item of the same types such as int, char, float or double. In this situation,
the concept of arrays comes into picture.
Definition: “Array is a collection of homogeneous data items under the same
name”.
Array allocates memory in a contiguous way, so that each data item can be
easily accessed with the help of index numbers. Each element is stored in a
contiguous memory location on RAM. The index numbers start from 0, 1, 2,
…, n-1. These indices are also called subscripts of an array. These indices are
used to locate the positions of elements within the array.
Let us consider, if a is the name of the array, the elements can be accessed as
a[0], a[1], a[2], … ,a[n-1]. a[0] is the name of the first element present at
position 0, a[1] is the name of the second element present at position 1 and so
on. a[i] is the element present at position i.
An array is mapped in a memory as,
10 20 30 40 50
a
0 1 2 3 4
Here, a is the name of the array, a[0] contains the element 10, a[1] contains
the element 20, a[2] contains the element 30, a[3] contains the element 40,
a41] contains the element 50. The subscripts always start from 0 to n-1.
Types of arrays:
- one-dimensional array
- two-dimensional array
- multidimensional array
one-dimensional array: an array in which each element is accessed by only
one subscript is called a one-dimensional array.
Declaration:
Syntax: data-type array-name[size];
Example: int a[10];
Here, int is a fundamental data type, a is a name of the array, and 10 enclosed
in a square bracket is a consecutive memory location allocated.
The total size of the array can be calculated as,
Total_size=size*(sizeof(data_type));
Where, size, is the number of elements in an array, sizeof() is a special
operator used to return the number of bytes that each data takes. Data type is
a type of data.
Here, in the above example, data type is int that takes 2 bytes of memory, and
there are 10 elements of the same type hence, 2*10=20 bytes.
Initialization of one-dimensional array: one-dimensional arrays can be
initialized as,
int a[5]={10,-20,-30,40,50};
Here, the value 10 stored in a[0], the value -20 stored in [1], the value -30
stored in [2], the value 40 stored in [3], the value 50 stored in [4]. Here is
how this map in memory.
10 -20 -30 40 50 a
0 1 2 3 4
If a lesser number of elements are assigned, then the remaining blocks are set
to zeros as shown below.
float height[5]={5.6,5.2,5.9};
Here, the value 5.6 is stored in height[0], the value 5.2 is stored in height[1],
the value 5.9 is stored in height[2]. Here is how this map in memory.
5.6 5.2 5.9 0.0 0.0 height
0 1 2 3 4
If an array does not assign any value then the array holds unexpected values
called garbage values. If the array is initialized explicitly, then the size can be
omitted.
int a[5]={10,-20-30,40,50};
this is equivalent to int a[]={10,-20-30,40,50};
Accessing the elements:
Let us consider the declaration int a[5];
We can read 5 elements in an array through the keyboard using the following
piece of code.
cout<<“Enter the elements\n”;
for(i=0;i<5;i++)
cin>>a[i];
similarly, to print all the 5 entered elements we can write the following piece
of code,
cout<<“The entered elements are\n”;
for(i=0;i<5;i++)
cout<<a[i];
// write a program to read and write the elements of an array
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10],n,i;
clrscr();
cout<<"How many elements? ";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"The entered elements are\n";
for(i=0;i<n;i++)
cout<<a[i]<<endl;
getch();
}
Output:
How many elements? 3
Enter the elements
10
20
30
The entered elements are
10
20
30
// Write a program to print even and odd numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10],n,i;
clrscr();
cout<<"How many elements? ";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Even numbers are:\n";
for(i=0;i<n;i++)
{
if(a[i]%2==0)
cout<<a[i]<<",";
}
cout<<"\b.";
cout<<"\nOdd numbers are:\n";
for(i=0;i<n;i++)
{
if(a[i]%2!=0)
cout<<a[i]<<",";
}
cout<<"\b.";
getch();
}
Output:
How many elements? 6
Enter the elements
1
2
3
4
5
6
Even numbers are:
2,4,6.
Odd numbers are:
1,3,5.
// Write a program to sort numbers in a descending order
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10],n,i,j,temp;
clrscr();
cout<<"How many elements? ";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"Descending elements are\n";
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
for(i=0;i<n;i++)
cout<<a[i]<<endl;
getch();
}
Output:
How many elements? 4
Enter the elements
3
1
4
2
Descending elements are
4
3
2
1
Two-dimensional arrays: an array in which each element can be accessed
with the help of two subscripts is called a two-dimensional array.
Two-dimensional array consists of rows and columns that forms a matrix
shown below,
Declaration:
Syntax: datatype array_name[row][column];
Example: int a[2][2];
Here, int is a data type, a is a name of the array and the first subscript
represents row and the second row represents column. In this example, an
array a stores 4 elements as there are 2 rows and two columns.
Initialization of two-dimensional array: two-dimensional arrays can be
initialized as follows,
int a[2][2]={10,20,30,40};
here, a is a two-dimensional array containing 2 rows and 2 columns and this
would map in memory as shown below:
a[0][0]=10 a[0][1]=20
a[1][0]=30 a[1][1]=40
if the number of values are less than the size of the array then the memory
blocks are set to zero.
int a[2][2]={
{10,20},
{30}
};
This initialization map in memory as shown below:
a[0][0]=10 a[0][1]=20
a[1][0]=30 a[1][1]=0
Accessing the elements:
Let us consider int a[2][2];
This example reads 4 elements, here we use nested for loops. The outer loop
represents row and the inner for loop represents column. The following code
fragment reads elements of two-dimensional arrays.
cout<<“Enter the elements\n”;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
cin>>a[i][j];
To print the read elements, we use the following piece of code
printf(“Entered elements are\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cout<<a[i][j]);
cout<<“\n”;
}
/* write a program to read and print the elements of two-dimensional
array*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],i,r,c,j;
clrscr();
cout<<"Enter the order of matrix: ";
cin>>r>>c;
cout<<"Enter the elements\n";
for(i=0;i<r;i++)
for(j=0;j<c;j++)
cin>>a[i][j];
cout<<"Matrix is\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
cout<<a[i][j];
cout<<"\n";
}
getch();
}
Output:
Enter the order of matrix: 2
2
Enter the elements
1
2
3
4
Matrix is
12
34
/* Write a program to check the frequency of a number in 2-dimensional
array*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a[10][10],i,r,c,j,count=0,ele;
clrscr();
cout<<"Enter the order of matrix: ";
cin>>r>>c;
cout<<"Enter the elements\n";
for(i=0;i<r;i++)
for(j=0;j<c;j++)
cin>>a[i][j];
cout<<"Matrix is\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
cout<<a[i][j];
cout<<"\n";
}
cout<<"Enter the element whose frequency is to be checked: ";
cin>>ele;
for(i=0;i<r;i++)
for(j=0;j<c;j++)
if(a[i][j]==ele)
count++;
cout<<"The element "<<ele<<" has appeared "<<count<<" times";
getch();
}
Output:
Enter the order of matrix: 3
3
Enter the elements
1
2
3
4
5
5
5
6
7
Matrix is
123
455
567
Enter the element whose frequency is to be checked: 5
The element 5 has appeared 3 times
Multi-dimensional array:
A multidimensional array is an array of n-dimensions. It is an array of arrays.
Each element of the array can be accessed by more than two subscripts is
called multidimensional arrays.

EXERCISES
1. Write a program to find the sum and average of n numbers.
2. Define an array. Explain its types.
3. How to declare a one-dimensional array? Explain with an example.
4. Explain the initialization of a one-dimensional array.
5. How to declare a two-dimensional array? Explain with an example.
6. Explain the initialization of a two-dimensional array.
7. Write a program to find the position of an element in an array.
8. Write a program to sort elements of an array.
9. Write a program to find the transpose of a matrix.
10. Write a program to find the sum of compatible matrices.
11. Write a program to find the product of compatible matrices.
12. Write a program to find the row and column sum of two-
dimensional arrays.
13. Write a program to find the sum of principal diagonal elements.
14. Write a program to check the frequency of a number in a 2-
dimensional array.
CHAPTER 6
BUILT-IN AND USER DEFINED
FUNCTIONS
Introduction:
When the program is lengthy and complex, the program has to be divided
into a number of small logical components that perform a specific task. This
finite set of instructions that performs a specific task is called module or sub
program.
Types of functions:
- library functions
- user-defined functions
Library functions: The functions which are already defined within the
compiler are called Library functions. These functions are present in the
header files that the user needs to include in his/her program.
Header files:
Different header files are used in C programs to meet the needs of the
programmer. Some of the header files and the functions present in them are
listed as below.
stdio.h header file: this is a standard input output header file used to perform
input and output operations using built-in functions. Some of the built-in
functions present in this header file are listed below.
printf, scanf , getchar, gets, putchar, puts etc.
string.h header file: this header file is used to manipulate string. Some of the
built-in functions present in this header file are listed below.
strcmp, strcat, strcmpi, strcpy, strlen, strlwr, strupr, etc.
stdlib.h header file: this is a standard library header file. Some of the built-in
functions present in this header file are listed below.
free, malloc, calloc, realloc, exit etc.
iostream.h header file: this is the input output stream header file. Some of
the built-in functions present in this header file are listed below.
open, close, get, getline, read, write, put, seekg, tellg, seekp, tellp, eof etc.
math.h header file: this header file contains mathematical functions. Some
of the built-in functions present in this header file are listed below.
cos, sin, tan, sqrt, abs, fabs, exp, pow, log etc.
character and string functions: a character constant is any letter, digit or
special symbol enclosed within a single pair of quotation marks. To perform
any operation on characters we have to include the ctype.h header file. Some
of the built-in functions present in this header file are listed below.
function description example
isalpha() It returns 1 if the isalpha(‘A’) returns 1
character is alphabet, isalpha(‘5’) returns 0
otherwise, it returns 0
isdigit() It returns 1 if the isdigit(‘A’) returns 0
character is digit, isdigit(‘5’) returns 1
otherwise, it returns 0
isalnum() It returns 1 if the isalnum(‘H’) returns 1
character is alphabet or isalnum(‘6’) returns 1
digit, otherwise, it isalnum(‘?’) returns 0
returns 0
isupper() It returns 1 if the isupper(‘K’) returns 1
alphabet is upper case, isupper(‘p’) returns 0
otherwise, it returns 0
islower() It returns 1 if the islower(‘K’) returns 0
alphabet is lower case, islower(‘p’) returns 1
otherwise, it returns 0
isspace() It returns 1 if the isspace(‘ ‘) returns 1
character is blank, isspace(‘\n’) returns 1
otherwise, it returns 0 isspace(‘J’) returns 0
ispunct() It returns 1 if the ispunct(‘#’) returns 1
character is a special ispunct(‘3’) returns 0
symbol, otherwise, it
returns 0
toupper() It converts lowercase toupper(‘a’) returns A
letter to uppercase
tolower() It converts uppercase tolower(‘A’) returns a
letter to lowercase
toascii() It converts the toascii(‘A’) returns 65
characters into its
ASCII value.
Inputting single character: we can input a single character using the get()
function as below.
char ch;
ch=cin.get();
Outputting single character: we can output a single character using the
put() function as below.
char ch;
ch=cin.get();
cout.put(ch);
// write a program to read and write a character
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
void main()
{
char ch;
clrscr();
cout<<"Enter the character: ";
ch=cin.get();
cout<<"Inputted character is ";
cout.put(ch);
getch();
}
Output:
Enter the character: K
Inputted character is K
Note: After executing the program press Alt+F5 to see the output in Turbo
C++ compiler.
String functions: string constants are the sequence of characters enclosed
within a pair of double quotation marks. Manipulation on strings is
performed by built-in functions present in the string.h header file. String is an
array of characters.
Declaration:
Syntax:
char array_name[size];
Example:
char s[20];
Initializing a string:
Example 1: char s[10]=”Programming”;
Here, 11 characters are present in Programming. The null character (\0) is
automatically inserted at the end of the string by the compiler.
Example 2: the string can also be initialized character-wise without
specifying its size.
char s[]={‘P’,’r’,’o’,’g’,’r’,’a’,’m’,’m’,’i’,’n’,’g’,’\0’};
Inputting a string: to input a string, C++ provides a function called
getline().
The general form is,
cin.getline(string,size);
Example:
char str[20];
cin.getline(str,20);
Outputting a string: to output a string, C++ provides a function called write.
The general form is,
cout.write(string,size);
Example:
char str[20];
cout.write(str,20);
// Write a program to input and output a string
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20];
clrscr();
cout<<"Enter the string: ";
cin.getline(str,20);
int l=strlen(str);
cout<<"Entered string is: ";
cout.write(str,l);
getch();
}
Output:
Enter the string: Hanumanth
Entered string is: Hanumanth
Note: After executing the program press Alt+F5 to see the output in Turbo
C++ compiler.
strlen() function: this function is used to return the total number of
characters present in the entered string. It returns an integer number
indicating the length of the string.
Syntax: variable=strlen(string);
Example: int l=strlen(“Programming”) returns 11
strcat() function: this function is used to combine two strings together. This
function is used to concatenate string2 to string1. The process of combining
two strings together.
Syntax: strcat(string1,string2);
Example: char s1[10]=”Lot”;
char s2[10]=”us”;
strcat(s1,s2);
here, string 2 appends at the end of string1 and it returns Lotus.
strcpy() function: this function is used to copy string2 in place of string1.
String1 will be replaced by string2.
Syntax:
strcpy(string1,string2);
Example: char s1[10]=”Lotus”;
char s2[10]=”Lilly”;
strcpy(s1,s2);
This returns Lilly.
strcmp() function: this function is used to compare a string alphabetically.
This function is case sensitive. i.e. both uppercase and lowercase letters are
different.
Syntax:
strcmp(string1,string2);
Example:
char s1[]=”Hello”;
char s2[]=”hello”;
strcmp(s1,s2) returns -1
strcmp(s2,s1) returns 1
if both the strings are equal then it returns 0.
strcmpi() function: this function is used to compare a string alphabetically.
This function is case insensitive. i.e. both uppercase and lowercase letters are
the same. If string1>string2 then it returns 1, if string1<string2 then it returns
-1, if string1 is equal to string2 then it returns 0.
Syntax:
strcmpi(string1,string2);
Example:
char s1[]=”Hello”;
char s2[]=”hello”;
strcmpi(s1,s2) returns 0
User-defined functions: the function defined by the user to solve his/her
problem is called user-defined function. In a user defined function, the user
uses his/her logic to solve a particular problem.
Advantages of user-defined functions:
- If there is a set of statements to be repeated several times in the
program, these statements can be replaced as a function and called
whenever and wherever required.
- A function can be developed and made available to more than one
program or to a group of programmers.
- Functions developed can be tested and debugged independently.
- If a program is divided into small modules, each module can be
developed by an individual programmer.
- If functions are developed, the number of lines of code decreases in
the program.
Syntax of user-defined function:

Where, return_type is the data type used to return a value by the function. if
nothing is returned to the calling function, then data type is void.
function_name is any valid identifier name that follows all the rules of
identifier. argument_list_with_declaration is used to declare all the variables
that receive value from the calling function (i.e. main() function). Local
variable declarations are the variables that are accessed within the function
definition. Executable statements perform necessary operations to solve
problems. If the function has a return type other than void then
return(expression) is needed.
// write a program to find the sum of two numbers
#include<stdio.h>
#include<conio.h>

void main()
{
int add(int a, int b); //function prototype
int a,b,sum;
clrscr();
printf(“Enter two numbers:\n”); calling function
scanf(“%d%d”,&a,&b);
sum=add(a,b); // function call
printf(“Sum=%d”,sum);
getch();
}

int add(int a, int b)


{
return(a+b); called function
}
Output:
Enter two numbers:
2
3
Sum=5
Calling function transfers control from it to another function by specifying
the name of that function and passing arguments. Called function that
receives the call and arguments from a calling function. function call is the
statement that is used to call the called function. when a function call is made,
the control jumps from calling function to the called function.
The general form of function call is,
variable=function_name(argument_list);
OR
variable=function_name();
Example: in the above example, the function call is,
sum=add(a,b);
Function prototype provides an interface for the compiler that tells a
particular function to be written. How we declare all the variables before
using them in the program, in the same way a function is declared in the
calling function before it is used.
The general form of function prototype is,
return_type function_name(type arg1, type arg2, …);
OR
return_type function_name(type, type, …);
Example: in the above example, int add(int a, int b); is the function
prototype.
When the function is called, the compiler checks the template to ensure that
proper arguments are passed and the correct type of value is returned. Any
violation leads to compiler error. The function prototype is terminated by
semicolon whereas the function definition does not terminate by semicolon.
Arguments in the function prototype are just placeholders, hence, arguments
name can be included or excluded. If names are included, they do not have to
match the argument names used in the function call or function definition.
Note: The main() function is used to return int by default. Otherwise, we
have to write it as void main() when the main() function returns nothing to
the operating system.
The general form of main() function is,
int main() void main()
{ {
Executable statements; OR executable statements;
return(0); }
}
Types of arguments: arguments are the variables that are declared in the
function header. The arguments are used to pass values from the calling
function to the called function.
There are two types of arguments,
- Actual arguments
- Formal arguments or parameters
Actual arguments: these are the variables that hold the actual values passed
by the programmer through the keyboard. The function call statement
contains the actual arguments. Actual arguments are present in the calling
function i.e. main() function.
Example, big=biggest(a,b,c);
Here, a, b, c are the actual arguments.
Formal arguments or parameters: these are the variables that hold the
copies of values passed by the actual arguments from calling function to
called function. The variables present in the function definition are formal
arguments or we call them as parameters. Parameters are present in the called
function i.e. function definition.
Example, int biggest(int a,int b,int c)
Here, the variables a,b,c of the function header are called parameters.
Scope of variables: scope of the variable is part of the program where the
variable can be accessed. If the variable is declared inside the block then it
can be accessed within that block of code. If the variable is declared before
the main function then it can be accessed anywhere in the program. Hence,
there are two scopes for the variables viz;
Local variables: the variables declared inside the function definition or
block of code can be accessed within that block are called local variables.
Example,
int add(int a, int b)
{
int x,y; // here x and y are local variables
-----
-----
}
Global variables: the variables declared before the main() function can be
accessed throughout the program are called global variables.
int a,b; // here a and b are global variables
void main()
{
int x,y; // here x and y are local variables
-----
-----
}
Categories of functions: there are five types of functions. They are:
- Functions with no arguments and no return type
- Functions with arguments and with no return type
- Functions with no arguments and with return type
- Functions with arguments and with return type
- Recursive functions
Functions with no arguments and no return type: in this type of function,
functions have no arguments and return value back to the calling function.
The general form is,
void function_name()
{
Statements
}
Example:
/* Write a program to print natural numbers using functions with no
arguments and no return type*/
#include<iostream.h>
#include<conio.h>
void main()
{
void natural(); //function prototype
clrscr();
natural(); //function call
getch();
}
void natural()
{
int i;
for(i=1;i<=10;i++)
cout<<i<<",";
cout<<"\b.";
}
Output:
1,2,3,4,5,6,7,8,9,10.
Functions with arguments and with no return type: these types of
functions receive arguments and do not return any value.
General form is,
void function_name(argument_list)
{
Statements;
}
Example:
// write a program to find the average of three numbers
#include<iostream.h>
#include<conio.h>
void main()
{
void average(int,int,int);
int a,b,c;
clrscr();
cout<<"Enter three numbers:\n";
cin>>a>>b>>c;
average(a,b,c);
getch();
}
void average(int x,int y,int z)
{
float sum,avg;
sum=x+y+z;
avg=sum/3.0;
cout<<"Average="<<avg;
}
Output:
Enter three numbers:
1
2
3
Average=2
Functions with no arguments and with return type: this type of function
receives no argument but it has return value.
The general form is,
return_type function_name()
{
Statements;
return(value);
}
Example:
// write a program to find the sum of two numbers
#include<iostream.h>
#include<conio.h>
void main()
{
int sum();
clrscr();
cout<<"Sum="<<sum();
getch();
}
int sum()
{
int a=10,b=5;
return(a+b);
}
Output:
Sum=15
Functions with arguments and with return type: this type of function has
arguments and also returns value.
The general form is,
return_type function_name(argument_list)
{
Statements;
return(value);
}
Example:
// write a program to calculate simple interest
#include<iostream.h>
#include<conio.h>
void main()
{
float simple(float,float,float);
float p,t,r;
clrscr();
cout<<"Enter the principal, time and rate of interest:\n";
cin>>p>>t>>r;
cout<<"Simple interest="<<simple(p,t,r);
getch();
}
float simple(float p,float t,float r)
{
return(p*t*r/100);
}
Output:
Enter the principal, time and rate of interest:
1000
5
5
Simple interest=250
Recursive functions: it is a function that calls by itself until a certain
condition is satisfied. This condition is called a stopping condition. If the
stopping condition is not satisfied, then the function enters into an infinity
loop.
The general form is,
return_type function_name(argument_list)
{
Statements;
return(function_name(argument_list));
}
/* write a program to find the factorial of a number using recursive
function*/
#include<iostream.h>
#include<conio.h>
void main()
{
int factorial(int);
int n,fact;
clrscr();
cout<<"Enter the number: ";
cin>>n;
fact=factorial(n);
cout<<"Factorial of "<<n<<"="<<fact;
getch();
}
int factorial(int n)
{
int f;
if(n==0) //stopping condition
return(1);
else
f=n*factorial(n-1);
return(f);
}
Output:
Enter the number: 4
Factorial of 4=24
Pass by value or call by value: when the values of the arguments are passed
from the calling function to a called function, the values are copied into the
called function. If any changes are made to the values in the called function,
there is no change in the original values within the calling function.
// write a program to demonstrate the use of pass by value
#include<iostream.h>
#include<conio.h>
void main()
{
void swap(int,int);
int a,b;
clrscr();
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before calling the function a="<<a<<" and b="<<b<<endl;
swap(a,b);
cout<<"After calling the function a="<<a<<" and b="<<b;
getch();
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Output:
Enter two numbers:
1
2
Before calling the function a=1 and b=2
After calling the function a=1 and b=2
Note: In this program the swapping of numbers does not take place.
Pass by reference or call by reference: when the reference of the arguments
is passed from the calling function to the called function, the values do not
copy into the called function. if any changes are made to the values in the
called function, then the original values get changed within the calling
function.
// Write a program to demonstrate the use of pass by reference
#include<iostream.h>
#include<conio.h>
void main()
{
void swap(int &,int &);
int a,b;
clrscr();
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before calling the function a="<<a<<" and b="<<b<<endl;
swap(a,b);
cout<<"After calling the function a="<<a<<" and b="<<b;
getch();
}
void swap(int &x, int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Output:
Enter two numbers:
1
2
Before calling the function a=1 and b=2
After calling the function a=2 and b=1
Default arguments:
To call a function in C++, we need not pass all the values for the arguments
to a function from the calling function (i.e. main() function). Default values
are assigned only in the function prototype. The value assignment for the
argument takes place from right to left. Some of the legal and illegal function
prototypes with default arguments are given below.
float interest (float principal, int time, float rate=0.15); // legal
float interest (float principal, int time=5, float rate=0.15); //legal
float interest (float principal=1000.0, int time=2, float rate=0.15); //legal
float interest (float principal=1500.0, int time, float rate=0.15); //illegal
float interest (float principal=500.0, int time=4, float rate); //illegal
float interest (float principal, int time=3, float rate); //illegal
default arguments are useful when some arguments always have the same
value.
// Write a program to demonstrate the use of default arguments
#include<iostream.h>
#include<conio.h>
void main()
{
float interest(float p, int t, float r=12.0);
float amount;
clrscr();
amount=interest(1500.0,3);
cout<<"By passing principal and time: simple interest="<<amount<<endl;
amount=interest(1200.0,2,5.0);
cout<<"By passing principal time and rate: simple interest="
<<amount<<endl;
getch();
}
float interest(float p,int t, float r)
{
return(p*t*r/100.0);
}
Output:
By passing principal and time: simple interest=540
By passing principal time and rate: simple interest=120
/* Write a program to find the area of a rectangle using default
arguments*/
#include<iostream.h>
#include<conio.h>
void main()
{
float area(float l=10.0, float b=12.0);
clrscr();
cout<<"By passing default arguments area="<<area()<<endl;
cout<<"By passing length 5.0 area="<<area(5.0)<<endl;
getch();
}
float area(float l, float b)
{
return(l*b);
}
Output:
By passing default arguments area=120
By passing length 5.0 area=60
Passing arrays to functions:
To pass an array to a function, pass the name of the array to the function.
Here we are referring to the address of the first element of the array. With the
help of this address, the function can access all the elements of the array.
Here the size of the array is not necessary.
// Write a program to concatenate two strings
#include<iostream.h>
#include<conio.h>
#include<string.h>
void concatenate(char str1[],char str2[]);
void main()
{
char s1[30],s2[30];
clrscr();
cout<<"Enter the first string: ";
cin.getline(s1,30);
cout<<"Enter the second string: ";
cin.getline(s2,30);
concatenate(s1,s2); //function call
cout<<"Concatenated string: "<<s1;
getch();
}
void concatenate(char str1[],char str2[])
{
int l1,l2,i;
l1=strlen(str1);
l2=strlen(str2);
for(i=0;i<l2;i++)
str1[l1+i]=str2[i];
str1[l1+l2]='\0';
}
Output:
Enter the first string: C++
Enter the second string: Programming
Concatenated string: C++Programming

EXERCISES
1. What are functions? Mention their types.
2. What is the difference between built-in function and user defined
function?
3. Explain any five header files.
4. Describe any five functions of ctype.h header.
5. Write a program to convert lowercase letters to uppercase letters.
6. Describe any five string functions with an example for each.
7. Write a program to find the length of the string.
8. Write a program to concatenate two strings.
9. Write a program to determine whether the string is palindrome.
10. Write a program to find the number of vowels and consonants in an
entered string.
11. Explain the advantages of user-defined functions.
12. What is a user defined function? Write its syntax.
13. Write a program to find the greatest of three numbers.
14. Write a program to find the square of a number.
15. Explain default arguments with programming examples.
16. Write a program to find the factorial of a number.
17. Explain types of arguments.
18. Write a program to concatenate two strings
19. Describe the use of scope of a variable with a programming
example.
CHAPTER 7
FUNCTION OVERLOADING
Introduction: we have learnt about polymorphism. Let us recall it once
again, poly means many, morph means forms. polymorphism means many
forms. The ability of the message to process in more than one form is called
polymorphism. The best examples for polymorphism are function
overloading and operator overloading. In this chapter we will learn function
overloading, in the forthcoming chapter we will learn operator overloading.

Definition: two or more functions having the same name with different
return type or different number of arguments. Function overloading is used in
a situation where, similar operation is to be performed on different types of
data. When an overloaded function is invoked, the C++ compiler chooses the
appropriate function by examining the number, data types and order of
arguments present in the function call. Function overloading can also be
defined as two or more functions having different return types with different
signatures. The signature means, function name followed by the parameter
list as shown below.

Need for function overloading:


Function overloading is used in a situation where we want to perform a
similar type of operation on different data types. Let us consider an example,
to perform an addition operation on different data types, say int, float, double
then function overloading is used. Function overloading indicates having the
same interface but many methods. Let us consider an example of an Epic
character called Ravan in Indian mythology, who had one body and ten faces.
The body of Ravana indicates an interface and ten heads represent many
methods.
Advantages of function overloading:
- Compiler checks the type of data, number of arguments and selects
appropriate functions. Thus, the code is executed faster.
- It is easy to understand the flow and debug.
- Code can be easily maintained.
- Creates an easy interface between programs and real-world objects.
Overloaded function example:
int add (int a, int b);
float add (float x, float y);
double add (double p, double q, double r);
Here, all the three overloaded functions having the same name – add that
interface and function 1 and 2 having the same number of arguments but their
return types are different.
Restrictions on overloaded functions:
- Each function in a set of overloaded functions must have a different
argument list.
- If typedef is used for naming functions, then the function is not
considered as a different type.
/* Write a program to find the sum of different types using function
overloading. */
#include<iostream.h>
#include<conio.h>
int add(int a, int b);
float add(float x, float y);
double add(double p, double q, double r);
void main()
{
clrscr();
cout<<"Addition of integers="<<add(10,20)<<endl;
cout<<"Addition of floating-point numbers="<<add(5.5,4.5,2.6)<<endl;
cout<<"Addition of double precision number="<<add(2.5,3.5,3.3)<<endl;
getch();
}
int add(int a, int b)
{
return(a+b);
}
float add(float x, float y, float z)
{
return(x+y+z);
}
double add(double p, double q, double r)
{
return(p+q+r);
}
Output:
Addition of integers=30
Addition of floating-point numbers=12.6
Addition of double precision number=9.3

/* Write a program to find the area of a square/rectangle/triangle using


function overloading. */

#include<iostream.h>
#include<conio.h>
int area(int a);
int area(int l, int w);
double area(double b, double h);
void main()
{
clrscr();
cout<<"Area of square="<<area(5)<<endl;
cout<<"Area of rectangle="<<area(5,10)<<endl;
cout<<"Area of triangle="<<area(2.0,3.0);
getch();
}
int area(int a) // area of a square
{
return(a*a);
}
int area(int l,int w) // area of a rectangle
{
return(l*w);
}
double area(double b,double h)
{
return(0.5*b*h);
}
Output:
Area of square=25
Area of rectangle=50
Area of triangle=3
// Write a program to find the biggest of set of parameters
#include<iostream.h>
#include<conio.h>
int big(int a, int b);
float big(float x, float y, float z);
double big(double p, double q, double r);
void main()
{
clrscr();
cout<<"Biggest of integer="<<big(15,23)<<endl;
cout<<"Biggest of floating-point="<<big(5.25,4.42,2.26)<<endl;
cout<<"Biggest of double-precision="<<big(6.36,2.3,3.3)<<endl;
getch();
}
int big(int a, int b)
{
if(a>b)
return a;
else
return b;
}
float big(float x, float y, float z)
{
float big=x;
if(y>big)
big=y;
if(z>big)
big=z;
return big;
}
double big(double p, double q, double r)
{
double big=p;
if(q>big)
big=q;
if(r>big)
big=r;
return big;
}
Output:
Biggest of integer=23
Biggest of floating-point=5.25
Biggest of double-precision=6.36
Inline functions: a function call involves the complex process of invoking a
function, passing parameters to the function, allocating storage for local
variables, thereby using extra time and memory space. It is possible to avoid
these overheads of a function by using an inline function.
Definition: inline function is a compact function call that replaces the
function call by function definition. The keyword inline is used to define an
inline function.
// Write a program to find a cube of a number
#include<iostream.h>
#include<conio.h>
inline int cube(int a)
{
return(a*a*a);
}
void main()
{
int n;
clrscr();
cout<<"Enter the number: ";
cin>>n;
cout<<"Cube of a number="<<cube(n);
getch();
}
Output:
Enter the number: 5
Cube of a number=125
Advantages of inline functions:
- The inline functions are compact function calls. Therefore, the size of
the object code is considerably reduced.
- The speed of execution of a program increases.
- Very efficient code can be generated.
- The readability of the program increases.
Disadvantages:
- As the body of the function is substituted in place of function call, the
size of the executable file size increases.
- Inline function occupies more memory.
- If there is any change in inline function then the function call this
inline function has to be recompiled.
When not to use inline function: an inline function should not be used in a
situation where,
- Inline function definition is too long or too complicated.
- The inline function is recursive.
- The inline function has looping constructs.
- The inline function has a switch or goto statements.

EXERCISES
1. What is function overloading? Give an example.
2. Write the advantages of overloaded functions.
3. Restrictions on overloaded functions.
4. Write a program to find the sum of different types using function
overloading.
5. Write a program to find the area of a square/rectangle/triangle
using function overloading.
6. Write a program to find the biggest of set of parameters
7. Explain what are inline functions.
8. Write a program to find a cube of a number
9. Write a program to find a square of a number
10. What are the advantages of inline functions?
11. What are the disadvantages of inline functions?
12. When not to use inline functions?
13. Write a program to find the largest of two numbers using an inline
function.
CHAPTER 8
FUNCTION TEMPLATES
Introduction: In the previous chapter we have learnt how to overload
functions. There is a disadvantage of using function overloading. Overloaded
functions perform similar operations on different data types. For this we have
to write separate code for each function definition. This creates an extra effort
for the programmers. This extra effort of writing similar functions again and
again we can use the new feature of C++ called function templates.
Definition: A function template is a method of writing a single generic
function for a group of similar functions designed to handle different data
types.
General form of function template:
template <class T> T function_name (T parameters)
{
//Function body with parameter type T
}
Where, T is a template parameter, class T is a template type parameter
enclosed with the angular braces (< >). class and template are keywords.
In order to find the greatest of numbers of different types using function
overloading can be written as follows:
int max(int x, int y)
{
return (x>y)?x:y;
}
float max(float x, float y)
{
return(x>y)?x:y;
}
double max(double x, double y)
{
return(x>y)?x:y;
}
char max(char x, char y)
{
return(x>y)?x:y;
}
There are disadvantages of writing similar functions with different data types
again and again. These are,
- Writing similar functions with different data types again and again is a
time-consuming process.
- Writing similar functions, they occupy more amount of storage space.
- When the error creeps in we have to correct it in the rest of the
functions.
In order to overcome these disadvantages, we use function templates, as
shown below.
template <class T>
T max (T x, T y)
{
return (x>y)?x:y;
}
Where T is the template parameter. This parameter is not necessarily T only,
you can write any identifier name for this parameter.
You can observe here, there is no specific data type. How does the compiler
select a particular function? When a template creates a specific type, a built-
in or user defined data type is substituted is called template instantiation.
/* Write a program to find the maximum of two numbers using a
function template. */
#include<iostream.h>
#include<conio.h>
template <class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
void main()
{
clrscr();
cout<<"Max(10,15)="<<max(10,15)<<endl;
cout<<"Max(10.25,15.75)="<<max(10.25,15.75)<<endl;
cout<<"Max('A','a')="<<max('A','a')<<endl;
cout<<"Max(25.235645,20.124587)="<<max(25.235645,20.124587)<<endl;
getch();
}
Output:
Max(10,15)=15
Max(10.25,15.75)=15.75
Max('A','a')=a
Max(25.235645,20.124587)=25.235645
Here, the function call max(10,15) makes the compiler select the function
max(int,int) to invoke, the function call max(10.25,15.75) makes the
compiler select the function max(float,float) to invoke. Similarly, done with
other types.
// Write a program to swap two data items of type int, float and double
#include<iostream.h>
#include<conio.h>
template <class T>
T swap(T &x, T &y)
{
T temp;
temp=x;
x=y;
y=temp;
return(0);
}
void main()
{
int a,b;
float p,q;
double m,n;
clrscr();
cout<<"Enter two integers: \n";
cin>>a>>b;
cout<<"Before interchanging: a="<<a<<" and b="<<b<<endl;
swap(a,b);
cout<<"After interchanging: a="<<a<<" and b="<<b<<endl;

cout<<"Enter two floating-point numbers: \n";


cin>>p>>q;
cout<<"Before interchanging: p="<<p<<" and q="<<q<<endl;
swap(p,q);
cout<<"After interchanging: p="<<p<<" and q="<<q<<endl;
cout<<"Enter two double precision numbers: \n";
cin>>m>>n;
cout<<"Before interchanging: m="<<m<<" and n="<<n<<endl;
swap(m,n);
cout<<"After interchanging: m="<<m<<" and n="<<n<<endl;

getch();
}
Output:
Enter two integers:
2
4
Before interchanging: a=2 and b=4
After interchanging: a=4 and b=2
Enter two floating-point numbers:
2.35
5.55
Before interchanging: p=2.35 and q=5.55
After interchanging: p=5.55 and q=2.35
Enter two double precision numbers:
12.22345
19.45365
Before interchanging: m=12.22345 and n=19.45365
After interchanging: m=19.45365 and n=12.22345
// Write a program to sort array elements using function template
#include <iostream.h>
#include<conio.h>
template<class T>
void sort(T a[ ])
{
int i,j;
for(i=0;i<5;i++)
for(j=i+1;j<5;j++)
if(a[i]>a[j])
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
for(i=0;i<5;i++)
cout<<a[i]<<endl;
cout<<endl;
}
void main( )
{
int intarray[5]={20, 10, 50, 40, 30};
float floatarray[5]={1.6, 2.0, 4.1, 1.8, 2.8};
char chararray[5]={'c','a','d','e','b'};
clrscr();
cout<<"SORTED INTEGER ARRAY"<<endl;
sort(intarray);
cout<<"SORTED FLOAT ARRAY"<<endl;
sort(floatarray);
cout<<"SORTED CHAR ARRAY"<<endl;
sort(chararray);
getch();
}
Output:
SORTED INTEGER ARRAY
10
20
30
40
50

SORTED FLOAT ARRAY


1.6
1.8
2
2.8
4.1

SORTED CHAR ARRAY


a
b
c
d
e
Function template instantiation: the process of substituting the template
type with various built-in and user-defined data types is known as template
instantiation.
/* Write a program to demonstrate the use of function template
instantiation. */
#include <iostream.h>
#include<conio.h>
template<class T>
T square(T n)
{
return(n*n);
}
void main()
{
int a=3;
float b=2.5;
clrscr();
cout<<"Square of "<<a<<"="<<square(a)<<endl;
cout<<"Square of "<<b<<"="<<square(b);
getch();
}
Output:
Square of 3=9
Square of 2.5=6.25
Here, the first function call square(a) in the statement
cout<<"Square of "<<a<<"="<<square(a)<<endl;
constructs the following code.
int square(int n)
{
return(n*n);
}
Similarly, the second call square(b) in the statement
cout<<"Square of "<<b<<"="<<square(b);
will construct the following code definition.
float square(float n)
{
return(n*n);
}
Template argument deduction: In order to instantiate a function template,
every template argument must be known, but not every template argument
has to be specified. When possible, the compiler will deduce the missing
template arguments from the function arguments. This occurs when a
function call is attempted and when an address of a function template is
taken.
// Write a program to demonstrate the template argument deduction
#include<iostream.h>
#include<conio.h>
template<class T>
T max(T* A, int l)
{
T big=A[0];
for(int i=0;i<l;i++)
{
if(A[i]>big)
{
big=A[i];
}
}
return big;
}
const int SIZE=5;
void main()
{
int a[SIZE]={10,40,30,60,20};
cout<<"Maximum value of the array is="<<max(a,SIZE)<<endl;
}
When the function template is instantiated, it is found that there is a mismatch
between the type of the first and the type of the corresponding function
parameter. However, due to array to pointer conversion array a is converted
to int * before deducing the type of the template argument.
Explicit template arguments:
When the template is instantiated with the two different types of arguments,
explicit template arguments are used.
Example,
template <class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
void main()
{
int a=10;
float b=10.5;
cout<<max(a,b); //error
}
Here, argument a is of type int and argument b is of type float. When the
function template is invoked, the template argument deduction deduces to
two different data types for the same template parameter, T. In this situation,
the compiler shows an error. To solve this problem, template argument
deduction has to be overridden. It is also necessary to specify explicitly the
template arguments as shown below.
max<float>(a,b); // explicit template argument is specified within a pair of
//angle brackets
This statement creates the following function.
float max(float x, float y)
{
return(x>y)?x:y;
}
Template compilation models: there are two template compilation models,
- Inclusion compilation model
- Separation compilation model
Inclusion compilation model: in this model the template definition is
included in the programs which have the instantiation of that template. The
template definition is written in a header file and this header file is included
in the program. Write the following code in a file called dummy.h
template<class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
Whenever the user wants to include the function max() in their programs,
then the user must use the dummy.h header file.
/* Write a program to demonstrate the use of inclusion compilation
model. */
#include<iostream.h>
#include<conio.h>
#include<dummy.h>
void main()
{
int a=10, b=20;
clrscr();
cout<<"Maximum value is "<<max(a,b);
getch();
}
Separation compilation model: in separation compilation model, we create
a header file containing function template declaration. And we will write
template definitions in the program file. Whenever a program uses the
instantiation of the function template, then we have to include in that program
only the header file but not the file containing the template definition.
Write the following declaration in the dummy.h header file.
template <class T> T max (T x, T y);
create one more file called program.cpp and write the following code.
export template<class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
Create one more file called max.cpp and write the following code.
#include<iostream.h>
#include<conio.h>
#include<dummy.h>
void main()
{
int a=10, b=20;
clrscr();
cout<<"Maximum value is "<<max(a,b);
getch();
}
The keyword export instructs the compiler to ensure the availability of the
template function in the programs when the function template instantiation is
generated.
Template explicit specialization: In some situations, the generic function
template will not give the proper semantics. To achieve this, we use template
explicit specialization.
Syntax:
template <>specialization_definition (function_parameters)
{
//function body
}
Overloading function templates:
function template overloading can be done similar to function overloading.
There must be different argument types and different numbers of arguments.
As shown below.
template <class T>
T max(T, T);
template <class U>
U max(U*, int);
// Write a program to demonstrate the use of template overloading.
#include<iostream.h>
#include<conio.h>
template<class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
template<class U>
U max(U *A, int size)
{
U big=A[0];
for(int i=0;i<size;i++)
{
if(A[i]>big)
{
big=A[i];
}
}
return big;
}
void main()
{
clrscr();
int arr[5]={15,25,20,10,30};
int a=50, b=60;
int l1,l2,sz;
sz=sizeof(arr);
cout<<"Maximum (a,b): "<<max(a,b)<<endl;
cout<<"Largest element of array is "<<max(arr,sz);
getch();
}
Output:
Maximum (a,b): 60
Largest element of array is 25
Overload resolution with instantiation:
In the template overloading we have studied that the functions will get
resolved while invoking. This is also applied to the template function
instantiation and normal function call. Let us see a programming example,
/* Write a program to demonstrate the use of overload resolution of
template instantiation and a normal function call. */
#include<iostream.h>
#include<conio.h>
template <class T>
T max(T x, T y)
{
return(x>y)?x:y;
}
double max(double a, double b)
{
return(a>b)?a:b;
}
void main()
{
int a=10,b=20;
double x=12.234, y=34.567;
clrscr();
cout<<"Big="<<max(a,b)<<endl;
cout<<"Big="<<max(x,y)<<endl;
cout<<"Big="<<max(x,b)<<endl;
getch();
}
Output:
Big=20
Big=34.567
Big=20
In the first and the second function call, there is an exact match between the
function arguments, thus instantiating successfully. The function template
instantiates to
int max(int ,int);
in the third function call there is a mismatch occurred between the arguments.
As the first argument is of type float and the second argument is of type int.
so it requires the standard type conversion. In this case the template function
emerges as the best viable function for calling.

EXERCISES
1. What is a function template? Explain with a programming
example.
2. Explain template argument deduction with an example.
3. Describe explicit template arguments with an example.
4. Briefly explain template inclusion compilation model
5. Explain separation compilation model with example.
6. Describe overloading function templates.
7. What is overload resolution with instantiation? Explain with a
programming example.
CHAPTER 9
POINTERS
Introduction: Till now we have studied how to declare variables of different
types. We know how many bytes that each type takes in memory, but we do
not know how these variables are stored in memory. The computer’s memory
is viewed as a consecutive block of locations identified by a unique number
called address. How we have got house numbers in a street, in a similar
fashion memory is organised. Everything we declare stores in a particular
memory location. Each data stored in memory location can be accessed by its
address.
Definition: a pointer is a special variable that holds the address of other
variables, structures and functions. It holds only the memory address of the
variable.
Advantages of pointers:
- With the help of pointers, efficient programs can be written.
- Memory is utilised properly.
- Allocate and deallocate memory at run-time (Dynamic).
- Easy to deal with hardware components of the computer.
- Pointer establishes the communication between program and data.
Pointer declaration: we have studied that the memory is organised in a
consecutive way. In order to understand pointers, we need to first understand
the organization of memory locations. Memory is organized as an array of
bytes. Each byte is identified by a unique number called address. Suppose we
have 1KB of memory then 1KB=1024 bytes, each byte is organized in a
sequential order with the subscript from 0 to 1023. The 0th subscript
represents the first memory location whereas the 1023rd subscript represents
the last memory location.
There are two operators used with pointers,
The address operator: & (ampersand).
The indirection operator: * (asterisk).
The address operator returns the address of the variable whereas the
indirection operator returns the content stored in the address.
When we declare a pointer variable with these two operators as,
int a, *iptr;
iptr=&a;
here, a and *iptr are common variable and pointer variable (any variable
preceded by *). In the second statement the address of a variable a is equated
to iptr.
If we initialize a variable with value as,
int a=10, *iptr;
iptr=&a;
then the same is represented in memory as follows,

Here, the value of a variable 10 is stored randomly, say, in memory address


3. In order to access the value 10, computers refer to the address of the
variable a i.e. memory location 3.
Pointer variables of any type can be declared as below,
int *iptr;
float *fptr;
char *cptr;
double *dptr;
void *vptr;
// Write a program to print the value and address of the variable
#include<iostream.h>
#include<conio.h>
void main()
{
int a, *iptr;
iptr=&a;
clrscr();
cout<<"Enter the value of a: ";
cin>>a;
cout<<"Address of a="<<iptr<<endl;
cout<<"Value stored in a="<<*iptr;
getch();
}
Output:
Enter the value of a: 10
Address of a=0x8f7cfff4
Value stored in a=10
Note: when a pointer to any type is declared, the compiler will allocate
memory only for the pointer, but not for the type to which it points. Here, the
address of the variable is not the same, it changes from computer to
computer.
// Write a program to find the size of a pointer
#include<iostream.h>
#include<conio.h>
void main()
{
int *iptr;
float *fptr;
char *cptr;
double *dptr;
void *vptr;
clrscr();
cout<<"Size of iptr="<<sizeof(iptr)<<endl;
cout<<"Size of fptr="<<sizeof(fptr)<<endl;
cout<<"Size of cptr="<<sizeof(cptr)<<endl;
cout<<"Size of dptr="<<sizeof(dptr)<<endl;
cout<<"Size of vptr="<<sizeof(vptr)<<endl;
getch();
}
Output:
Size of iptr=2
Size of fptr=2
Size of cptr=2
Size of dptr=2
Size of vptr=2
Note: whether the pointer is pointing to an int, a float, a char, a double or a
void type, the size of the pointer is always 2 bytes.
Operations on pointers: we know that the pointer points to a memory
address which is an integer number, hence, we can perform some of the
following operations on it.
- An integer value can be added to a pointer.
Example, int *iptr;
iptr=iptr+2;
- An integer value can be subtracted from a pointer.
Example, int *iptr;
iptr=iptr-2;
- One pointer variable can be subtracted from another, if both are
pointing to the elements of the same array.
Example, int a[3]={5,10,15};
int *iptr1,*iptr2,*iptr3;
iptr1=&a[0];
iptr2=&a[1];
iptr3=iptr1-iptr2;
- We can compare two pointers, if they are of the same type.
Example, int *iptr1, *iptr2;
(iptr1==iptr2)
(iptr1!=iptr2)
(iptr1<=iptr2) etc.
- A pointer variable can be assigned a NULL value;
Example, int *iptr;
iptr=NULL;
- A pointer variable can be equated to another pointer provided both
pointers are of the same type.
Example, int *iptr2, *iptr2;
iptr1=iptr2;
the operations that cannot be performed on the pointers are,
- Addition of two pointers.
- Subtraction of one pointer from another pointer when they do not point
to the same array.
- Multiplication of two pointers.
- Division of two pointers.
Pointers and arrays:
Let us consider, int a[5];

a[0] a[1] a[2] a[3] a[4]


The elements of the array can be referred to in the program as a[0],a[1],…
a[4]. When the program is compiled, the address of all these subscripts is not
required, only the address of the first block element is required. The name of
an array itself designates some memory location. When the program wants to
access the next element, it calculates the address of the next element by
adding the value of the index number.
Pointers and functions:
Like other variables, pointer variables can be passed to the functions. Passing
pointers to the functions can be carried out in three ways.
- Call by reference with pointer arguments
- Call by value or pass by value
- Call by reference with reference arguments
Invoking functions by passing the references:
In this method, the formal arguments become reference to the actual
arguments in the calling function. called function refers to the original values
by different names. Thus, the called function works with the original data and
any change in the values gets reflected to the data.
// Write a program to swap two numbers using pass by reference method
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
void swap(int *, int *);
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before swapping a="<<a<<" and b="<<b<<endl;
swap(&a,&b);
cout<<"After swapping a="<<a<<" and b="<<b;
getch();
}
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output:
Enter two numbers:
10
20
Before swapping a=10 and b=20
After swapping a=20 and b=10
Call by value: when the values of the arguments are passed to the function,
these values are copied into the storage of function parameters.
// Write a program to swap two numbers using call by value method

#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
void swap(int,int);
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before swapping a="<<a<<" and b="<<b<<endl;
swap(a,b);
getch();
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"After swapping a="<<a<<" and b="<<b;
}
Output:
Enter two numbers:
100
200
Before swapping a=100 and b=200
After swapping a=200 and b=100
When we pass references as arguments to the function, the function receives
the lvalue to these arguments rather than their actual values as in call by value
method. This helps the function to note down the memory location of the
argument and can take the address of the argument or modify its value.
/* Write a program to swap two numbers using call by reference with
reference arguments*/
#include<iostream.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
void swap(int &,int &);
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Before swapping a="<<a<<" and b="<<b<<endl;
swap(a,b);
getch();
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"After swapping a="<<a<<" and b="<<b;
}
Output:
Enter two numbers:
250
500
Before swapping a=250 and b=500
After swapping a=500 and b=250
Memory allocation of pointers:
There are two ways to allocate memory to pointers,
- Static memory allocation
- Dynamic memory allocation
Static memory allocation: in this allocation, the amount of memory to be
allocated is predicted and pre known. This memory is allocated during the
compilation itself. All the declared variables declared normally, are allocated
memory statically.
Example, int a; /* this declaration of a variable a allocates 2 bytes of
memory at compile time*/
Dynamic memory allocation: in dynamic memory allocation, the amount of
memory to be allocated is not known. This allocation can be done at time of
execution.
We can allocate and deallocate memory location for the object at run time
using new and delete operators respectively. These operators allocate
memory for objects from a pool called free store. The object allocated
memory using the new operator should be deleted using the delete operator.
Otherwise, it results in memory leak.
To allocate memory of type integer,
int *iptr=new int;
OR
int *iptr;
iptr=new int;
To allocate memory for array,
int *iptr=new int[20];
To allocate memory for structure,
student *sp=new student;
// Write a program to demonstrate dynamic memory allocation
#include<iostream.h>
#include<conio.h>
int *ptr;
void fun()
{
ptr=new int;
*ptr=10;
}
void main()
{
clrscr();
fun();
cout<<"Value of *ptr="<<*ptr;
getch();
}
Output:
Value of *ptr=10
In this program, memory allocated is not deleted. Hence, it creates orphaned
memory block that lead to adverse effects on the system.
delete the object allocated memory dynamically as,
delete object_name;
example,
delete ptr;
To delete array, delete [] iptr;
To delete structure, delete sp;
// Write a program to illustrate the use of new and delete operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int *iptr=new int(10);
float *fptr=new float(2.25);
char *cptr=new char('H');
cout<<"Integer value is "<<*iptr<<endl;
cout<<"Floating-point value is "<<*fptr<<endl;
cout<<"Character value is "<<*cptr<<endl;
delete iptr;
delete fptr;
delete cptr;
getch();
}
Output:
Integer value is 10
Floating-point value is 2.25
Character value is H
Free store: it is a pool of unallocated memory used to allocate to a program
dynamically at run-time.
This free memory is also called heap memory, which is reserved to use only
at run-time allocation.
Memory leak: if the variables, that are allocated memory dynamically, are
not freed by using the operator delete, the memory block remains occupied
even after the program execution terminates. Such memory blocks are known
as orphaned memory blocks. These orphaned memory blocks, when
increased in number, bring adverse effects on the system. This situation is
called memory leak.
/* write a program to sort elements of an array in an ascending order
using dynamic memory allocation*/
#include<iostream.h>
#include<conio.h>
void main()
{
int i, n, j, temp;
clrscr();
cout<<"How many elements?";
cin>>n;
int *a=new int[20];
cout<<"Enter the elements:\n";
for(i=0;i<n;i++)
cin>>*(a+i);
cout<<"The sorted elements are\n";
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
for(i=0;i<n;i++)
cout<<a[i]<<endl;
getch();
}
Output:
How many elements?5
Enter the elements:
30
50
10
40
20
The sorted elements are
10
20
30
40
50
EXERCISES
1. What is a pointer? Write its advantages.
2. Mention the operators used with pointers.
3. Write a program to display the value and address of a variable.
4. Explain operation performed on pointers.
5. Describe pointer initialization with programming examples.
6. How is memory allocated dynamically in C++?
7. Write a program to sort elements of an array using dynamic
memory allocation technique.
8. Write a program to find the location of an element in an array
using a pointer.
CHAPTER 10
STRUCTURES AND UNIONS
Introduction: Till now we have studied variables of simple types like, int,
char, float and double. Variables of these types represent one item of
information such as, a mark, an account, a height etc. In order to collect such
variables together we use structures. We have studied arrays; arrays are
collections of Homogeneous types of data under the same name. But
structures are collections of Heterogeneous data items under the same name.
structures are exactly opposite to that of arrays, because arrays are collections
of similar types whereas, structures are collections of different types.
Consider a situation where we want to process the information of an
employee, where we process the data such as employee code, salary, name,
designation etc. All these data are of different types, employee code is of int,
salary is of float, and name and designation are of type char. Hence, in order
to process more than one type of data structures are used.
Definition: A structure is a collection of the same or different simple
variables. Some variables can be int, some can be float and so on. The data
items in a structure are called members of the structure. Once the structure is
defined, the user-defined data type is defined.
Syntax of structure:
struct structure_name
{
Data_type1 member_name-1;
Data_type2 member_name-2;

Data_type-n member_name-n;
};
Where, structure definition begins with the keyword struct followed by
structure_name that is a valid identifier name given to the structure, that
obeys all the rules of defining identifier. Curly open brace indicates the
beginning of the body of structure definition. Under the curly open brace
collection of data members are declared with their types. Curly closing brace
and semicolon indicate that this is the termination point of structure
definition.
Structure definition serves as a blueprint or template, which does not
hold any space in memory of a computer system. Once the structure is
defined, you can create any number of variables (or objects) of that type.
Each object occupies the memory space (memory space depends on the
number of variables declared in the structure definition and how many bytes
each variable takes).
Let us consider an example of structure definition,
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
};
student s1,s1,s3;
The above structure definition consists of four members, rollno int type,
name char type holds 20 characters, combination char type holds 4 characters
and percentage float type. As we already know that, int takes 2 bytes, char
takes 1 byte, float takes 4 bytes of memory. Once we create variables s1,s2,s3
and so on, of student type, each variable takes 30 bytes of memory space. The
following diagram depicts how memory is allocated to each element.
/* Write a program to show the number of bytes each object takes in
structure*/
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
}s1;
clrscr();
cout<<"The size of object s1="<<sizeof(s1);
getch();
}
Output:
The size of object s1=30
Accessing the elements of a structure:
The members of the structures can be accessed using dot operators. it is not
possible to access the members of the structure directly. Instead you can
access members of the structure as, structure variable (or object) followed by
dot operator and followed by member name.
Structure_variable.member_name;
The dot operator is also called a member access operator.
In the above example, if we wish to access rollno, it is accessed for the first
object as, s1.rollno. Similarly, name can be accessed as, s1.name and so on.
// write a program illustrate the use of dot operator
#include<iostream.h>
#include<conio.h>
void main()
{
struct test
{
int a;
int b;
}t;
clrscr();
t.a=10;
t.b=20;
cout<<"The value of a="<<t.a<<endl;
cout<<"The value of b="<<t.b;
getch();
}
Output:
The value of a=10
The value of b=20
Note: here, in the above example, object t is declared soon after the curly
closing brace of the class definition. Each member a and b are accessed using
the dot operator.
// write a program to read and write the information of a student
#include<iostream.h>
#include<conio.h>
void main()
{
struct student
{
int rollno;
char name[20];
char combination[4];
float percentage;
};
struct student s1;
clrscr();
cout<<"Enter the roll number: ";
cin>>s1.rollno;
cout<<"Enter the name of the student: ";
cin>>s1.name;
cout<<"Enter the combination: ";
cin>>s1.combination;
cout<<"Enter the percentage: ";
cin>>s1.percentage;
cout<<"Roll number="<<s1.rollno<<endl;
cout<<"Name of the student="<<s1.name<<endl;
cout<<"Combination="<<s1.combination<<endl;
cout<<"Percentage="<<s1.percentage<<endl;
getch();
}
Output:
Enter the roll number: 1
Enter the name of the student: Hanumanth
Enter the combination: pcmc
Enter the percentage: 80.33
Roll number=1
Name of the student=Hanumanth
Combination=pcmc
Percentage=80.330002
Initializing a structure: the structure can be initialized as follows,
employee e={
10,
“Hanumanth”,
“CEO”,
50000000.00
};
Similarly, a student structure definition can also be initialized as,
student s1={
1,
“Priyanka”,
“PCMC”,
77.20
};
Embedded structures: A structure within another structure is called
embedded structure. It is also called nested structures. The embedded
structure declared first and the outer structure declared next.
Example 1:
struct distance
{
int feet;
float inches;
};
struct room
{
distance length;
distance breadth;
};
The structure room contains another structure, distance. i.e. the structure
distance is enclosed within the room structure. The definition of structure
distance precedes the definition of the structure room.
Example 2:
struct date
{
int day;
int month;
int year;
};
struct employee
{
int empid;
date doj;
float salary;
}e;
To access the member empid, we write, e.empid. To access the member day,
month and year of date of joining (doj), we write, e.doj.day, e.doj.month and
e.doj.year respectively. To access the member salary, we write, e.salary.
// write a program to receive and display the information of an employee
#include<iostream.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
void main()
{
struct employee
{
int empid;
struct date doj;
float salary;
}e;
clrscr();
cout<<"Enter the employee id: ";
cin>>e.empid;
cout<<"Enter the Date of Joining: ";
cin>>e.doj.day>>e.doj.month>>e.doj.year;
cout<<"Enter the salary: ";
cin>>e.salary;
cout<<"Employee Information\n";
cout<<"Employee id="<<e.empid<<endl;
cout<<"Employee Date of Joining="<<e.doj.day<<"-"<<e.doj.month<<"-"
<<e.doj.year<<endl;
cout<<"salary="<<e.salary;
getch();
}
Output:
Enter the employee id: 100
Enter the Date of Joining: 14 06 2021
Enter the salary: 100000
Employee Information
Employee id=100
Employee Date of Joining=14-6-2021
salary=100000
Array of structures: Till now we have studied how to process one or more
object’s data but in order to process huge data, we require the use of arrays.
When we want to process, say, 1000 employees’ information, we cannot
create individual objects like e1,e2,…e1000. It is very cumbersome, instead
we can use an array of structure, where we create a huge number of objects
by simply writing the array size as below.
struct employee
{
int empid;
char name[20];
char designation[15];
float salary;
}e[1000];
Here, e is an array of 1000 elements. Each element of the array e is a separate
structure of type employee.
e[0].empid access the employee id of the first employee. Whereas,
e[1000].empid access the employee id of the 1000th employee. The same is
depicted in the following diagram.

// write a program to demonstrate the use of array of structures


#include<iostream.h>
#include<conio.h>
struct employee
{
int empid;
char name[20];
char designation[15];
}e[1000];
void main()
{
int i,n;
clrscr();
cout<<"How many employees? ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter the employee id, name, and designation of employee "
<<i+1<<endl;
cin>>e[i].empid;
cin>>e[i].name;
cin>>e[i].designation;
}
cout<<"\nEmployee Information\n";
cout<<"---------------------------------------\n";
cout<<"empid\tname\tdesignation\n";
cout<<"---------------------------------------\n";
for(i=0;i<n;i++)
{
cout<<e[i].empid<<"\t";
cout<<e[i].name<<"\t";
cout<<e[i].designation<<endl;
}
cout<<"---------------------------------------\n";
getch();
}
Output:
How many employees? 2
Enter the employee id, name, and designation of employee 1
1
Swaroop
Cashier
Enter the employee id, name, and designation of employee 2
2
Raj
Manager

Employee Information
---------------------------------------
empid name designation
---------------------------------------
1 Swaroop Cashier
2 Raj Manager
---------------------------------------
Type definition (typedef):
The keyword typedef is used to alias the data types. That is, giving one more
name to the data types. It creates synonyms for the data types.
Syntax:
typedef old_data_type new_data_type;
Here, typedef is a keyword used to alias the data type. old_data_type may be
basic or user defined or derived data types. new_data_type is any user
defined valid identifier name.
Example 1: typedef int wholeno;
Here, int is an old data type whereas, wholeno is a new data type.
Example 2: typedef float realno;
Here, float is an old data type whereas, realno is a new data type.
Similarly, we can also give aliasing names to the structure.
Example:
struct employee
{
int empid;
char name[20];
float salary;
};
typedef struct employee my_staff;
Here, employee is an old data type whereas, my_staff is a new data type.
With the help of new data type, we can create objects as,
my_staff Ramesh;
Here, my_staff is acting as a data type which is employee type and Ramesh is
an object of type my_staff.
// write a program to demonstrate the use of typedef
#include<iostream.h>
#include<conio.h>
void main()
{
struct author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
};
typedef struct author book_writer;
book_writer bw;
clrscr();
cout<<"Enter the number of books published: ";
cin>>bw.no_of_books;
cout<<"Enter the name of the author: ";
cin>>bw.author_name;
cout<<"Enter the name of the publisher: ";
cin>>bw.publisher;
cout<<"Enter the price of the book: ";
cin>>bw.price;
cout<<"------------------------------------------------------\n";
cout<<"\t\tBook Information\n";
cout<<"------------------------------------------------------\n";
cout<<"Number of books: "<<bw.no_of_books<<endl;
cout<<"Author name: "<<bw.author_name<<endl;
cout<<"Publisher: "<<bw.publisher<<endl;
cout<<"Price: "<<bw.price<<endl;
cout<<"------------------------------------------------------\n";
getch();
}
Output:
Enter the number of books published: 8
Enter the name of the author: Hanumanth
Enter the name of the publisher: Self
Enter the price of the book: 600
------------------------------------------------------
Book Information
------------------------------------------------------
Number of books: 8
Author name: Hanumanth
Publisher: Self
Price: 600
------------------------------------------------------
Array of structure initialization:
Array of structure can also be initialized in the following way,
struct student
{
int rollno;
char name[20];
float percentage;
};
stud s[]={
1, “Priyanka”, 77.25,
2, “Sneha”, 50.00,
3, “Soniya”, 65.33,
4, “Swaroop”, 45.00,
5, “Raj”, 42.66,
6, “Rakshita”, 93.00,
};
Here, s is an array of structures whose size is not specified. The values
initialized will define the size, here, 6 students’ information is provided
hence, the size of the array is 6. The amount of memory occupied depends on
the number of objects initialized.
Unions: Union is also a collection of heterogeneous elements, similar to
structures. But there is a difference between how structure members and
union members store. Each member of a structure is assigned its own
memory location. Whereas, all union members share a common memory
location. Thus, unions are used to save memory.
Syntax of union definition:
union union_name
{
Data_type1 member_name-1;
Data_type2 member_name-2;

Data_type-n member_name-n;
};
Here, union is a keyword, union_name is a valid identifier name, data_type1,
data_type2…data_type-n are types of data and member_name-1,
member_name-2,… member_name-n are variables.
Example:
union author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
}a;
Accessing union members:
Accessing union members is similar to accessing structure members using
dot operators. Even the arrow (->) operator can be used. In the above
example, we can access each member by using dot operator as,
a.no_of_books;
a. author_name;
a. publisher;
a.price;
Here, a is an object that holds the memory space of the maximum size of
member declared in a union. In the above example, no_of_books occupies 2
bytes, author_name occupies 20 bytes, publisher occupies 15 bytes, prince
occupies 4 bytes. The maximum amount of memory is occupied by the
author_name variable because its size is 20 which is maximum among all
other variables present in the union. Hence, the size of the object is 20 bytes
in this example.
// Write a program to return the size of union object
#include<iostream.h>
#include<conio.h>
void main()
{
union author
{
int no_of_books;
char author_name[20];
char publisher[15];
float price;
}a;
clrscr();
cout<<"The size of the union object a is "<<sizeof(a)<<" bytes";
getch();
}
Output:
The size of the union object a is 20 bytes
EXERCISES
1. Write a difference between arrays and structures.
2. Write the syntax of defining structure.
3. Write a program to accept rollno, name, combination and
percentage of a student and print the same.
4. Explain how to initialize structure.
5. What are nested structures? Explain with an example.
6. Describe an array of structures with a programming example.
7. Write a program to accept empid, name, designation and compute
gross salary of the employee. (Hint: Gross salary=basic+da+hra).
8. What is union? Explain how union is different from structure.
9. Write a program to accept and display the information of 100
students.
10. Write a program to accept the information of a teacher such as,
name, designation, department, qualification and process the data
and print the same.
CHAPTER 11
CLASSES
Introduction: Every problem in an Object-Oriented Programming is viewed
as an object rather than procedure. Real world objects can be represented as
data variables. Data variables can be identified as rollno, percentage,
attendance etc. When these real-world objects are represented as data in
computers, they can also be manipulated or processed by using functions in
C++. For instance, rollno of a student can be updated, the percentage of
marks can be calculated and so on. To combine the data variables i.e. objects
along with appropriate functions for manipulation of these objects, the
concept of classes was introduced in object-oriented programming.
The concept of object-oriented programming begins with the use of classes
and objects. A class creates a new data type. It is a collection of both data and
functions in a single unit. We have studied the concept of combining data
elements into a group called structure in the previous chapter. The data
elements in a class are called data members and functions are called as
function members of the class.
Class definition: class is a fundamental building block of object-oriented
programs. It consists of both data and functions that operate on these data. A
class is a collection of objects of similar types. A class is a user-defined data
type.
The general form of a class is,
class class_name
{
private: data_member;
function_member;
public: data_memeber;
function_member;
protected: data_member;
function-member;
};
The class head is made up of the keyword class followed by the name of the
class. Class body is enclosed within the curly open and close brackets. The
class body consists of both data members and function members. The class
definition is terminated by a semicolon. The class name is any valid identifier
name that satisfies all the rules for writing identifier names. class is a
keyword and it should be written in lowercase letters only.
There are three member access specifiers, viz, private, public and protected.
All of these three are keywords.
Example:
class student
{
private: int rollno;
char name[20];
float percentage;
public: void getdata();
void putdata();
};
Here, the class name student is a new type identifier that is used to declare an
instance of that class type. The class contains three data members (rollno,
name, percentage) and two function members (getdata() and putdata()).
Data members are declared under private access specifiers whereas member
functions are declared under public access specifiers. If no member access
specifier is specified, by default it is private. The function members getdata()
and putdata() are used to write instructions to perform operations on member
data. These two member functions only can provide access to get member
data from outside the class. Therefore, the data cannot be accessed by any
other function that is not the member of the class.
Once the class is defined, we can create any number of objects of class type,
because class is user defined data type. Each object created is separated by a
comma.
Accessing members of the class:
The members of a class can be data or function members. The public data
members of the class can be accessed with the help of member access
operator dot(.) operator.
The general form for accessing members of the class is,
class_object.data_member;
class_object.function_member(arguments);
Let’s learn an example of defining a class and its object.
// Write a program to find the sum of two numbers
#include<iostream.h>
#include<conio.h>
class example
{
int a,b;
public: void getdata()
{
cout<<"Enter two numbers:\n";
cin>>a>>b;
}
void putdata()
{
cout<<"Sum of two numbers: "<<(a+b);
}
};
void main()
{
example e;
clrscr();
e.getdata();
e.putdata();
getch();
}
Output:
Enter two numbers:
2
4
Sum of two numbers: 6
Here, a and b are data members declared without access specifiers. That is,
both a and b are private members of the class by default. The function
member getdata() and putdata() are used to receive and display the sum of
two numbers. The function members getdata() and putdata() are user-defined
functions. You can write any valid identifier names to the user-defined
functions. And e is an object of type example. We can access members of the
class as, observe in main() function, object e is followed by dot(.) operator
followed by getdata(). Similarly, object e is followed by dot (.) operator
followed by putdata(). Execution of C++ programs starts from main()
function only. At least and at most one main() function must be present in a
C++ program. When the compiler encounters with the statement e.getdata();
the compiler searches for the function definition and it executes all the
instructions present in it and then control transfers back to main() function’s
next statement, when the compiler encounters with the statement e.putdata();
the compiler searches for the function definition and it executes all the
statements present in it and then control transfers back to main() function
once again, then it terminates. If you are eager to see the flow of control that
jumps from one place to another, then you press the F7 function button (in
Turbo C++ compiler) to trace the program flow.
// Write a program to process student information
#include<iostream.h>
#include<conio.h>
class student
{
private: int rollno;
char name[20];
float percentage;
public: void getdata()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the percentage: ";
cin>>percentage;
}
void putdata()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name="<<name<<endl;
cout<<"Percentage="<<percentage<<endl;
}
};
void main()
{
student s;
clrscr();
s.getdata();
s.putdata();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Hanumanth
Enter the percentage: 80.33
Roll number=1
Name=Hanumanth
Percentage=80.330002
Significance of access specifiers:
An object is defined to be an instance of a class. Every member of a class is
specified by three levels of access protection for providing security to the
data. The access specifiers define the scope of data. In C++ there are three
types of access specifiers,
- private
- public
- protected
private: A member data can only be accessed by the member function.
members declared under private are accessible only within the class. If no
access specifier is mentioned, by default, members are private.
Example: private: int a,b;
public: Members declared under public can be accessed by any function
outside the class definition.
Example:
// Write a program to demonstrate the use of public access specifiers.
#include<iostream.h>
#include<conio.h>
class room
{
int height;
public: int length, breadth;
void set_height(int a)
{
height=a;
}
int put_height()
{
return height;
}
};
void main()
{
room r;
clrscr();
r.length=5;
r.breadth=10;
r.set_height(15);
cout<<"Length="<<r.length<<endl;
cout<<"Breadth="<<r.breadth<<endl;
cout<<"Height="<<r.put_height()<<endl;
getch();
}
Output:
Length=5
Breadth=10
Height=15
protected: Members declared under protected can be accessed by the
member functions, friend function and the members of the derived class
(Inheritance) . We will study Inheritance
in detail in the forthcoming chapter.
Example:
// Write a program to demonstrate the use of protected access specifiers.
#include<iostream.h>
#include<conio.h>
class room
{
protected: double width;
};
class smallroom:room
{
public: void getdata(double w)
{
width=w;
}
double putdata()
{
return width;
}
};
void main()
{
smallroom r;
clrscr();
r.getdata(5.0);
cout<<"Width of room: "<<r.putdata();
getch();
}
Output:
Width of room: 5
Here, protected member width from class room is accessible within another
class called smallroom. The room is a base class and smallroom is a derived
class. The room class inherits properties to the smallroom class.
Member functions: Member functions can be defined inside the class
definition as well as outside the class definition.
- Inside class definition
- Outside class definition
Member function inside class definition: we have already learnt how to
define member function inside the class definition. Let us learn one more
programming example that shows how to define member functions inside the
class definition.
/* Write a program to find the area of a rectangle by defining member
functions inside the class definition. */
#include<iostream.h>
#include<conio.h>
class rectangle
{
int length, breadth;
public: void input_data()
{
cout<<"Enter the length and breadth:\n";
cin>>length>>breadth;
}
int compute_area()
{
return(length*breadth);
}
void output_data()
{
cout<<"Area of a rectangle="<<compute_area();
}
};
void main()
{
rectangle r;
clrscr();
r.input_data();
r.output_data();
getch();
}
Output:
Enter the length and breadth:
10
5
Area of a rectangle=50
Function definition outside the class definition: function can be declared
and it can be defined outside the class definition using scope resolution (::)
operator.
The general form for writing function definition outside the class definition
is,
return_type class_name::member_function(arg1, arg2,…,arg-n)
{
Function body;
}
/* Write a program to perform arithmetic operations by defining
functions outside the class definition. */
#include<iostream.h>
#include<conio.h>
class arithmetic
{
float a,b;
public: float sum(float a, float b);
float diff(float a, float b);
float prod(float a, float b);
float div(float a, float b);
};
float arithmetic::sum(float a, float b)
{
return(a+b);
}
float arithmetic::diff(float a, float b)
{
return(a-b);
}
float arithmetic::prod(float a, float b)
{
return(a*b);
}
float arithmetic::div(float a, float b)
{
return(a/b);
}
void main()
{
arithmetic ar;
float a,b;
clrscr();
cout<<"Enter two numbers:\n";
cin>>a>>b;
cout<<"Sum="<<ar.sum(a,b)<<endl;
cout<<"Difference="<<ar.diff(a,b)<<endl;
cout<<"Product="<<ar.prod(a,b)<<endl;
cout<<"Division="<<ar.div(a,b)<<endl;
getch();
}
Output:
Enter two numbers:
20
5
Sum=25
Difference=15
Product=100
Division=4
Array of objects: we know that, once we define a class, we can create any
number of objects of that type. If we have a huge number of objects to be
created and process the data, in such a situation we use an array of objects.
An array having class type is called an array of objects.
// Write a program to show the use of array of objects
#include<iostream.h>
#include<conio.h>
class student
{
int rollno,m1,m2,m3;
public: float avg();
void receive();
void display();
};
void student::receive()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the subject 1 marks: ";
cin>>m1;
cout<<"Enter the subject 2 marks: ";
cin>>m2;
cout<<"Enter the subject 3 marks: ";
cin>>m3;
display();
}
float student::avg()
{
return(m1+m2+m3)/3.0;
}
void student::display()
{
cout<<"Percentage="<<avg()<<endl;
}
void main()
{
student s[3]; // array of objects
clrscr();
for(int i=0;i<3;i++)
s[i].receive();
getch();
}
Output:
Enter the roll number: 1
Enter the subject 1 marks: 66
Enter the subject 2 marks: 80
Enter the subject 3 marks: 75
Percentage=73.666664
Enter the roll number: 2
Enter the subject 1 marks: 55
Enter the subject 2 marks: 50
Enter the subject 3 marks: 51
Percentage=52
Enter the roll number: 3
Enter the subject 1 marks: 45
Enter the subject 2 marks: 87
Enter the subject 3 marks: 80
Percentage=70.666664
Here, the receive() function member has display() function call. Hence, the
control transfers to display() function. The display() function has an avg()
function call. The control transfers to avg() function and it returns the average
value of three subject marks to the display() function. Then the control
transfers back to the main() function and then it repeats the same procedure
for next two students' information.
Objects as function arguments: A function can receive an object as a
function argument. It is similar to any other data type being sent as a function
argument.
/* Write a program to demonstrate the use of objects as function
arguments. */
#include<iostream.h>
#include<conio.h>
class sum
{
int a,b;
public: void getdata()
{
cout<<"Enter the value of a and b:\n";
cin>>a>>b;
}
void putdata(sum x,sum y)
{
int c;
c=x.a+y.b;
cout<<"Sum of "<<a<<" and "<<b<<"="<<c;
}
};
void main()
{
sum s;
clrscr();
s.getdata();
s.putdata(s,s);
getch();
}
Output:
Enter the value of a and b:
5
5
Sum of 5 and 5=10
friend function: We learnt that private and protected members of a class
cannot be accessed from outside the class in which they are declared. In some
situations where two classes must share a common function. C++ allows the
common function to be shared between the two classes by making the
common function as a friend to both the classes, hence allowing the function
to have access to the private data of both of these classes.
A friend function is a non-member function that is a friend of a class. The
friend function is declared within a class with the prefix friend. But it should
be defined outside the class like a normal function without the prefix friend.
It is just like a friend(s) who is using your books, pencil and other
belongings.
// Write a program to show the use of a friend function
#include<iostream.h>
#include<conio.h>
class data
{
int a,b;
public: void getdata(int i, int j);
friend int sum(data d);
};
void data::getdata(int i,int j)
{
a=i;
b=j;
}
int sum(data d)
{
return(d.a+d.b);
}
void main()
{
data obj;
clrscr();
obj.getdata(20,40);
cout<<"Sum="<<sum(obj);
getch();
}
Output:
Sum=60
Remember the following points while using the friend function.
- A friend function is a non-member function that has full access rights
to the private and protected members of the class.
- It cannot be called using the object of that class. It can be invoked like
any normal function.
- It can be declared anywhere and it is not affected by the access
specifiers (private, public and protected).
- Friend functions are normal external functions that are given special
privileges.
- It cannot access the member variables directly and has to use an object
name. member name.
- The friend function is declared with the friend keyword. But while
defining it should not use either friend keyword or :: operator.
Nested classes: A class can be enclosed within another. It is similar to the
nested structures.
// Write a program to illustrate the use of nested classes
#include<iostream.h>
#include<conio.h>
class student
{
int rollno;
char name[20];
float per;
public: class date
{
int day,month,year;
public: void set_date(int dd, int mm, int yy)
{
day=dd;
month=mm;
year=yy;
}
void displaydate()
{
cout<<"Date of birth="<<day<<"-"<<month<<"-"<<year<<endl;
}
};
void input_data()
{
cout<<"Enter the roll number: ";
cin>>rollno;
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the percentage: ";
cin>>per;
}
void output_data()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name of the student="<<name<<endl;
cout<<"Percentage="<<per<<endl;
}
};
void main()
{
int d,m,y;
student s;
clrscr();
student ::date dob;
s.input_data();
cout<<"Enter the date of birth:\n";
cin>>d>>m>>y;
cout<<"Student\'s information is as follows\n";
s.output_data();
dob.set_date(d,m,y);
dob.displaydate();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Hanumanth
Structure Class
Defined with the keyword struct Defined with the keyword class
Members are public by default. Members are private by default.
Contains data members and
Contains only data members.
function members.
Enter the percentage: 78
Enter the date of birth:
1
1
1990
Student's information is as follows
Roll number=1
Name of the student=Hanumanth
Percentage=78
Date of birth=1-1-1990
Here, we have created the object for the nested class as student ::date dob.
Difference between structure and class:
EXERCISES
1. Define class with its syntax and an example.
2. Explain the member access specifiers used in C++.
3. Describe how to access members of the class.
4. Write a program to show how to define a function definition
outside the class definition.
5. Describe array objects with a programming example.
6. Explain how to pass objects as function arguments.
7. Write a program to illustrate the use of nested classes.
8. What is the difference between structure and class?
CHAPTER 12
CONSTRUCTORS AND
DESTRUCTORS
Introduction: We know that, we cannot initialize the data members of the
class directly. We have learnt how to initialize the data members of the class
using member functions. In this chapter we will learn how to initialize the
data members automatically using a special member function called
constructor and how to delete the objects initialized by the constructor using
a function member called destructor to achieve memory optimization. In case
of constructors, we won’t call a constructor function explicitly.
Automatically, constructor functions will get invoked and executed. This
relieves the burden of calling the functions explicitly by the programmer.
Definition: A constructor is a special member function which is used to
initialize the data members of the class automatically.
Rules for writing a constructor function:
- A constructor always has the same name as that of the class name.
- There is no return type for constructors (not even void).
- A constructor should be declared in the public section.
- A constructor is invoked automatically when objects are created.
Constructors can have default arguments.
- It is not possible to refer to the address of the constructor.
- The constructors make implicit calls to the operators new and delete
when memory allocation is required.
- Constructors can be overloaded.
- A constructor cannot be declared as virtual.
- The const or volatile class objects cannot be initialized with a
constructor.
- The constructors are not inherited.
Example:
#include<iostream.h>
#include<conio.h>
class volume
{
int length, width, height;
public: volume() //Constructor
{
length=10;
width=15;
height=20;
}
void display()
{
cout<<"Volume="<<length*width*height;
}
};
void main()
{
volume v;
clrscr();
v.display();
getch();
}
Output:
Volume=3000
Observe that volume() is a special member function, that does not return any
type, not even void and name of the function is same as that of the class
name. It is a member function which is used to initialize the data members
length, width and height automatically. In the main() function we have not
called the volume() function explicitly. It is invoked automatically as soon as
the object of the class is created. The display() function is a user-defined
function used to show the volume as output.
Types of constructors: there are three types of constructors,
- Default constructor.
- Parameterized constructor.
- Copy constructor.
Default constructor: A constructor that does not receive any arguments is
called default constructor. As it receives no arguments, it is also called a zero
argument constructor.
Features of default constructor:
- Default constructor invokes automatically when an object of the class
is declared.
- All objects of a class are initialized to the same set of values by the
default constructor.
- If different objects are to be initialized with different values, it cannot
be done using the default constructor.
The program above depicts the use of default constructor. Let us take one
more programming example that illustrates the use of default constructor.
// Write a program to demonstrate the use of default constructor
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
public: student();
void display();
};
student::student()
{
rollno=1;
strcpy(name,"Hanumanth");
}
void student::display()
{
cout<<"Roll number="<<rollno<<endl;
cout<<"Name="<<name<<endl;
}
void main()
{
student s;
clrscr();
s.display();
getch();
}
Output:
Roll number=1
Name=Hanumanth
Observe that, the constructor student() is defined outside the class definition
with scope resolution operator (::).
Disadvantages of default constructor:
- All objects of a class are initialized to the same set of values by the
default constructor.
- If different objects are to be initialized with different values, it cannot
be done using the default constructor.
Parameterized constructors: A constructor that takes one or more
arguments is called a parameterized constructor. With this constructor, it is
possible to initialize different objects with different values. These
constructors are also invoked automatically, whenever objects with
arguments are created. The parameters are used to initialize the object.
Features of parameterized constructors:
- The parameterized constructor can be overloaded.
- For an object created with one argument, constructor with only one
argument is invoked and executed.
- The parameterized constructor can have default arguments and default
values.
The constructor can be invoked in one of the following three ways.
- Explicit call
- Implicit call
- Initialization at the time of declaration with = operator
Explicit call: The declaration of an object is followed by assignment
operator; constructor name and argument list are enclosed in parenthesis.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
float percentage;
public: student(int rno, char nm[], float per)
{
rollno=rno;
strcpy(name,nm);
percentage=per;
}
void display()
{
cout<<"Student roll number: "<<rollno<<endl;
cout<<"Student name: "<<name<<endl;
cout<<"Student percentage: "<<percentage<<endl;
}
};
void main()
{
int r;
char n[20];
float p;
clrscr();
cout<<"Enter the roll number: ";
cin>>r;
cout<<"Enter the name: ";
cin>>n;
cout<<"Enter the percentage: ";
cin>>p;
student s=student(r,n,p); // Explicit call
s.display();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Sneha
Enter the percentage: 55
Student roll number: 1
Student name: Sneha
Student percentage: 55
Implicit call: The declaration of the object is followed by an argument list
enclosed in parentheses.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
float percentage;
public: student(int rno, char nm[], float per)
{
rollno=rno;
strcpy(name,nm);
percentage=per;
}
void display()
{
cout<<"Student roll number: "<<rollno<<endl;
cout<<"Student name: "<<name<<endl;
cout<<"Student percentage: "<<percentage<<endl;
}
};
void main()
{
int r;
char n[20];
float p;
clrscr();
cout<<"Enter the roll number: ";
cin>>r;
cout<<"Enter the name: ";
cin>>n;
cout<<"Enter the percentage: ";
cin>>p;
student s(r,n,p);
s.display();
getch();
}
Output:
Enter the roll number: 1
Enter the name: Priyanka
Enter the percentage: 77
Student roll number: 1
Student name: Priyanka
Student percentage: 77
Initialization at the time of declaration with = operator: This way of
calling is used for the constructor with exactly one argument. In this method,
declaration is followed by assignment operator and value to be initialized.
#include<iostream.h>
#include<conio.h>
class data
{
int a;
public: data(int x)
{
a=x;
}
void display()
{
cout<<a;
}
};
void main()
{
data d=5;
clrscr();
cout<<"Value of a=";d.display();
getch();
}
Output:
Value of a=5
Copy constructor: It is a parameterized constructor used to copy one object
to another object of the same type.
Features of copy constructor:
- Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
/* Write a program to find the factorial of a number using a copy
constructor. */
#include<iostream.h>
#include<conio.h>
class fact
{
int n;
public: fact(int a);
int factorial();
};
fact::fact(int a)
{
n=a;
}
int fact::factorial()
{
int fact=1,i;
for(i=1;i<=n;i++)
fact=fact*i;
return fact;
}
void main()
{
int n1;
clrscr();
cout<<"Enter the number: ";
cin>>n1;
fact obj(n1);
fact copy=obj;
cout<<"Before copying: "<<n1<<"!="<<obj.factorial()<<endl;
cout<<"After copying: "<<n1<<"!="<<copy.factorial()<<endl;
getch();
}
Output:
Enter the number: 6
Before copying: 6!=720
After copying: 6!=720
Constructor overloading:
A class may contain more than one constructor. How we were overloading
functions, in a similar way constructor can also be overloaded.
/* Write a program to compute simple interest using overloaded
constructors. */
#include<iostream.h>
#include<conio.h>
class simple
{
float p,t,r,si;
public: simple()
{
}
simple(float a, float b, float c)
{
p=a;
t=b;
r=c;
}
void compute()
{
cout<<"Simple interest="<<p*t*r/100.0;
}
};
void main()
{
int pri, time, rate;
clrscr();
cout<<"Enter the principal amount: ";
cin>>pri;
cout<<"Enter the time: ";
cin>>time;
cout<<"Enter the rate of interest: ";
cin>>rate;
simple s(pri,time,rate);
s.compute();
getch();
}
Output:
Enter the principal amount: 1000
Enter the time: 5
Enter the rate of interest: 6
Simple interest=300
// Write a program to demonstrate the use of overloaded
constructors.
#include<iostream.h>
#include<conio.h>
class sample
{
int a,b;
public: sample()
{
a=10;
b=20;
}
sample(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"a="<<a<<" and b="<<b<<endl;
}
};
void main()
{
sample s1,s2(30,40);
clrscr();
cout<<"Sample 1: ";s1.display();
cout<<"Sample 2: ";s2.display();
getch();
}
Output:
Sample 1: a=10 and b=20
Sample 2: a=30 and b=40
Destructors: As we are familiar with the constructor, constructor is a special
member function which is used to initialize the data members of the class
automatically. In the same way, a destructor is a special function which is
used to deallocate memory location occupied by the object initialized by the
constructor. A destructor is a special member function that will be executed
automatically when an object is destroyed. The destructor name is the same
as that of the class and it is preceded by the tilde (~) symbol.
Rules for writing destructor are,
- The destructor name is the same as that of the class name, preceded by
the tilde (~) symbol.
- Destructors do not have a return value (not even void).
- Destructors take no arguments. Therefore, destructors cannot be
overloaded.
- The most common use of a destructor is to deallocate memory
allocated for the object by the constructor.
- Constructor should be declared in the public section.
The general form of defining destructor is,
class class_name
{
private: data_members;
public: class_name(); // Constructor
~class_name(); // Destructor
};
// Write a program to demonstrate the use of destructor
#include<iostream.h>
#include<conio.h>
class example
{
int a;
public: example()
{
a=10;
cout<<"Value of a in constructor: "<<a<<endl;
}
void display()
{
a=20;
cout<<"Value of a in display function: "<<a<<endl;
}
~example()
{
cout<<"Destructor invokes";
}
};
void main()
{
clrscr();
example e;
e.display();
getch();
}
Output:
Value of a in constructor: 10
Value of a in display function: 20
Destructor invokes
Note: The text “Destructor invokes” in destructor will not be printed if you
execute the program. Trace this program by pressing F7 (in Turbo C++
Compiler) to reach control flow to the destructor. Before the compiler prints
the text present in the destructor, the object created and initialized by the
constructor will be destroyed. Hence, it is not going to show the text present
in the destructor.
If multiple objects are created, these objects are destroyed in the reverse order
of their creation. For example, the declaration statement
example e1, e2, e3;
object e1 creates first, next e2 and then e3. These objects destroy e3 first, e2
next and e1 last.
/* Write a program to demonstrate that the objects will destroy in
reverse order of their creation in destructor. */
#include<iostream.h>
#include<conio.h>
int count=0;
class example
{
public: example()
{
count++;
cout<<"In the constructor, object "<<count<<" is created."<<endl;
}
~example()
{
cout<<"In destructor, object "<<count<<" is destroyed."<<endl;
count--;
}
};
void main()
{
clrscr();
example e1,e2,e3;
getch();
}
Output:
In the constructor, object 1 is created.
In the constructor, object 2 is created.
In the constructor, object 3 is created.
In destructor, object 3 is destroyed.
In destructor, object 2 is destroyed.
In destructor, object 1 is destroyed.

EXERCISES
1. What is a constructor? Explain the rules for writing constructor.
2. Write a program to demonstrate the use of constructor.
3. What are the types of constructors?
4. Explain the default constructor with an example.
5. Describe the parameterized constructor with an example.
6. Explain the copy constructor with a programming example.
7. Explain constructor overloading with an example.
8. What is a destructor? Explain with a programming example.
CHAPTER 13
OPERATOR OVERLOADING
Introduction: The operator used in one instance for a specific purpose may
not be used by the same operator for the same purpose in another instance.
Meaning that, an operator performs differently at different instances of time.
It does not change its syntax but it changes its semantics. Let us consider
examples such as, the operator ‘+’ is used with the numbers and acts as an
arithmetic operator, when the same operator is used with the string then it
acts as a concatenation operator. Similarly, >> and << operators are used as
input and output operators with cin and cout objects respectively. These same
operators act differently when used with bitwise operations, they act as a
bitwise right shift operator and bitwise left shift operator. When we consider
an * (asterisk) operator, when used with two or more operands acts as an
arithmetic product whereas, when used as unary operator, acts as a pointer. In
this chapter we will learn how different operators behave differently. This
process of using operators differently at different instances of time is called
operator overloading.
The general form to define operator overloading is,
return_type class_name::operator opr(argument_list)
{
// function body
}
Here, operator is a keyword used before the built-in operator and the rest of
the syntax is similar to the function definition.
Example 1:
void string::operator + (string s1, string s2)
{
// string concatenation
}
void product::operator * (product e1, product e2)
{
// multiplication of two objects
}
Overloadable operators: Following table shows a list of operators that can
be overloaded.
Assignment Arithmetic Relational Logical Bitwise Increment Special
operator operator operator operator operator and operator
decrement
operator
= + < ! & ++ ,
- <= && | -- []
* > || ~ ()
/ >= ^ ->
% == << ->*
+= != >> new
-= <<= new[]
*= >>= delete
/= &= delete[]
%= |=
^=

Non-overloadable operators: Following table shows a list of operators that


they cannot be overloaded.
Operator Name
:: Scope resolution operator.
. Member access operator.
?: Ternary operator.
sizeof() Special operator used to return the number of bytes that each
data type takes.
.* Member selection through pointers to function.

Let us consider the overloading of + operator with objects a and b then,


c=a+b;
This works fine.
If we change the same statement as,
c=a+6;
Here, the left hand side operand is an object and the right hand side operand
is a constant value. Still it works fine.
Now, if we change the same statement as,
c=6+a;
then this doesn’t work properly. This is because the left-hand side operand is
not an object. To invoke the operator, member function, the left-hand side
operand of an overloaded operator must be an object. To overcome this
problem, a friend function is used.
/* Write a program to demonstrate a friend function for an unary minus
(-) operator overloading. */
#include<iostream.h>
#include<conio.h>
class dot
{
int a,b;
public: void getdata(int x, int y)
{
a=x;
b=y;
}
void display()
{
cout<<"a="<<a<<" b="<<b<<endl;
}
friend void operator -(dot &d);
};
void operator -(dot &d)
{
d.a=-d.a;
d.b=-d.b;
}
void main()
{
dot d;
clrscr();
cout<<"Dot is in first quadrant"<<endl;
d.getdata(5,10);
d.display();
cout<<"Now, the dot is int third quadrant"<<endl;
-d;
d.display();
getch();
}
Output:
Dot is in first quadrant
a=5 b=10
Now, the dot is int third quadrant
a=-5 b=-10
/* Write a program to add 1 to each element of an array using the friend
function. */
#include<iostream.h>
#include<conio.h>
class add
{
int a[3];
public: void getdata();
void display();
friend add operator + (int n, add b);
};
void add::getdata()
{
cout<<"Enter the array elements\n";
for(int i=0;i<3;i++)
cin>>a[i];
}
void add::display()
{
for(int i=0;i<3;i++)
cout<<a[i]<<endl;
}
add operator + (int n, add b)
{
add c;
for(int i=0;i<3;i++)
c.a[i]=n+b.a[i];
return c;
}
void main()
{
add x,y;
clrscr();
x.getdata();
y=1+x;
cout<<"After adding 1 to each element"<<endl;
y.display();
getch();
}
Output:
Enter the array elements
10
20
30
After adding 1 to each element
11
21
31
Operator =: The assignment operator is used to assign one class object to
another object of the same class.
/* Write a program to illustrate the use of assignment operator
overloading. */
#include<iostream.h>
#include<conio.h>
#include<string.h>
class emp
{
int empid;
char name[20];
float salary;
public: emp(int eid, char ename[], float sal)
{
empid=eid;
strcpy(name,ename);
salary=sal;
}
void operator = (emp &e)
{
empid=e.empid;
strcpy(name,e.name);
salary=e.salary;
}
void display()
{
cout<<"Employee number="<<empid<<endl;
cout<<"Employee name="<<name<<endl;
cout<<"Employee salary="<<salary<<endl;
}
};
void main()
{
clrscr();
emp e1(1,"Swaroop",10000.0);
emp e2=e1;
cout<<"Details of the first employee:\n";
e1.display();
cout<<"\nDetails of the second employee:\n";
e2.display();
getch();
}
Output:
Details of the first employee:
Employee number=1
Employee name=Swaroop
Employee salary=10000

Details of the second employee:


Employee number=1
Employee name=Swaroop
Employee salary=10000
Operator [ ]: This is a subscript operator. When overloaded, we can create a
new object and can access elements from it.
// Write a program to illustrate operator [ ] overloading
#include<iostream.h>
#include<conio.h>
class array
{
int a[3];
public: array();
int &operator [] (int i)
{
if(i>3)
{
cout<<"Out of bounds"<<endl;
return a[0];
}
return a[i];
}
};
array::array()
{
for(int i=0;i<3;i++)
a[i]=i;
}
void main()
{
array a;
clrscr();
cout<<"Value of a[1]: "<<a[1]<<endl;
cout<<"Value of a[2]: "<<a[2]<<endl;
cout<<"Value of a[5]: "<<a[5]<<endl;
getch();
}
Output:
Value of a[1]: 1
Value of a[2]: 2
Out of bounds
Value of a[5]: 0
Operator (): The operator () is a function call operator. it can be overloaded
for class objects. By overloading the function call operator we can create
function objects.
// Write a program to illustrate the function call () operator overloading.
#include<iostream.h>
#include<conio.h>
class distance
{
int feet, inches;
public: distance()
{
feet=0;
inches=0;
}
distance(int f, int i)
{
feet=f;
inches=i;
}
distance operator()(int a, int b, int c)
{
distance d;
d.feet=a+b+5;
d.inches=b+c+10;
return d;
}
void display()
{
cout<<"Feet="<<feet<<" and Inches="<<inches<<endl;
}
};
void main()
{
distance d1(2,4),d2;
clrscr();
cout<<"First distance=";d1.display();
d2=d1(1,3,5); //invoke () operator
cout<<"Second distance=";d2.display();
getch();
}
Output:
First distance=Feet=2 and Inches=4
Second distance=Feet=9 and Inches=18
Operator ->: This operator can be overloaded for class objects.
/* Write a program to calculate the area of a room using operator ->
overloading. */
#include<iostream.h>
#include<conio.h>
class room
{
int length,breadth;
public: room(int l,int b)
{
length=l;
breadth=b;
}
void area()
{
cout<<length*breadth;
}
};
class roomptr
{
room *ptr;
public: roomptr(const room &rp)
{
*ptr=rp;
}
room operator* ()
{
return *ptr;
}
room *operator->() //-> operator function
{
return ptr;
}
};
void main()
{
clrscr();
room r(10,20);
roomptr rp(r);
cout<<"Area of room = ";
rp->area();
getch();
}
Output:
Area of room = 200
Operators ++ and -- : the increment and decrement operators can be
overloaded for a class object. The increment operator increases the value of a
variable by 1.
// Write a program to demonstrate overloading of increment operators.
#include<iostream.h>
#include<conio.h>
class counter
{
int count;
public: counter()
{
count=0;
}
counter(int a)
{
count=a;
}
void display()
{
cout<<"Count="<<count<<endl;
}
void operator ++()
{
++count;
}
};
void main()
{
counter c;
clrscr();
c.display();
++c;
c.display();
++c;
c.display();
getch();
}
Output:
Count=0
Count=1
Count=2
Like increment operator, decrement operator can also be overloaded. The
decrement operator is used to decrease the value of a variable by 1.
// Write a program to illustrate the overloading of decrement operators.
#include<iostream.h>
#include<conio.h>
class counter
{
int count;
public: counter()
{
count=3;
}
counter(int a)
{
count=a;
}
void display()
{
cout<<"Count="<<count<<endl;
}
void operator --()
{
--count;
}
};
void main()
{
counter c;
clrscr();
c.display();
--c;
c.display();
--c;
c.display();
getch();
}
Output:
Count=3
Count=2
Count=1
Operators new and delete: Whenever dynamic memory allocation is
required, we use new and delete operators. These two operators can also be
overloaded.
The syntax for overloading the new operator,
void* operator new(size_t size);
it must have a void* return type and take a first parameter of type size_t. the
size_t is present in the header file stddef.h.
// Write a program to illustrate overloading of new and delete operators.
#include<iostream.h>
#include<conio.h>
#include<stddef.h>
#include<stdlib.h>
class employee
{
int empid;
float salary;
public: employee()
{
cout<<"In constructor\n";
}
employee(int empid, float salary)
{
this->empid=empid;
this->salary=salary;
}
void display()
{
cout<<"Employee id="<<empid<<endl;
cout<<"Salary of the employee="<<salary<<endl;
}
void* operator new(size_t size)
{
void *p=::operator new(size);
return p;
}
void operator delete(void *p)
{
cout<<"Overloading delete operator\n";
free(p);
}
};
void main()
{
clrscr();
employee *p=new employee(10,15000);
p->display();
delete p;
getch();
}
Output:
Employee id=10
Salary of the employee=15000
Overloading delete operator

EXERCISE
1. What is operator overloading? Write its syntax and example.
2. List overloadable and non-overloadable operators.
3. Write a program to illustrate the use of the overloading minus (-)
operator.
4. Write a program to illustrate the use of overloading plus (+)
operator.
5. Write a program to illustrate the use of an overloading operator =.
6. Write a program to illustrate the use of overloading [ ] operator.
7. Write a program to illustrate the use of overloading () operator.
8. Write a program to illustrate the use of overloading -> operator.
9. Write a program to illustrate the use of overloading ++ and --
operator.
10. Write a program to illustrate the use of overloading new and delete
operators.
CHAPTER 14
CLASS TEMPLATES
Introduction: class template is a generic type that can be reused for different
data types. C++ allows function template and class template. In chapter 8 we
have already studied function templates. Now in this chapter we’ll learn class
templates.
Class template definition: A single generic container class that is capable of
handling different data types.
The general form of a class template is,
template <class template_parameter>
class class_name
{
Class body;
};
Example:
template <class T>
class example
{
T a,b;
public: void getdata();
void putdata();
};
Here, template parameter T is replaced by built-in or user-defined data types
when the class template is instantiated. If the template instantiated to int then
the private members a and b will become int type. if the template is
instantiated to float then the private members a and b will become float type.
/* Write a program to find the sum of two numbers using a class
template. */
#include<iostream.h>
#include<conio.h>
template <class T>
class sum
{
T a,b,sum;
public: void getdata();
void add();
};
template <class T>
void sum <T> ::getdata()
{
cout<<"Enter two numbers:\n";
cin>>a>>b;
}
template <class T>
void sum <T> :: add()
{
T sum;
sum=a+b;
cout<<a<<"+"<<b<<"="<<sum<<endl;
}
void main()
{
clrscr();
sum <int> intobj;
sum <float> floatobj;
cout<<"Integer sum\n";
intobj.getdata();
intobj.add();
cout<<"Floating-point sum\n";
floatobj.getdata();
floatobj.add();
getch();
}
Output:
Integer sum
Enter two numbers:
4
6
4+6=10
Floating-point sum
Enter two numbers:
3.2
5.5
3.2+5.5=8.7
Class template instantiation: the process of substituting the template
parameter with the various built-in and user-defined data types is known as
template instantiation. If this instantiation is able to generate a class from the
generic class template definition then it is called the class template
instantiation.
// Write a program
#include<iostream.h>
#include<conio.h>
template <class T>
class array
{
T *ptr;
int size;
public: array(T a[], int s);
void display();
};
template<class T>
array<T>::array(T a[],int s)
{
ptr=new T[s];
size=s;
for(int i=0;i<size;i++)
ptr[i]=a[i];
}
template<class T>
void array<T>::display()
{
for(int i=0;i<size;i++)
cout<<" "<<*(ptr+i);
cout<<endl;
}
void main()
{
clrscr();
int a[5]={2,4,6,8,10};
array<int> b(a,5);
b.display();
getch();
}
Output:
2 4 6 8 10
Member functions of a class definition: A member function can be defined
inside or outside the class definition. This concept is already learnt. If you
want to define a function outside the class definition then there is a special
member syntax as shown below. (This is already covered in the above
programming examples).
template <class T>
void sum<T> :: getdata()
{
cout<<”Enter two numbers:\n”;
cin>>a>>b;
}
/* Write a program to find the biggest of numbers and characters by
defining member functions outside the class definition. */
#include<iostream.h>
#include<conio.h>
template <class T>
class biggest
{
T a,b;
public: T max(T a, T b);
void getdata();
void display();
};
template <class T>
void biggest<T>::getdata()
{
cout<<"Enter two numbers or characters:\n";
cin>>a>>b;
}
template <class T>
T biggest<T>::max(T a, T b)
{
return(a>b)?a:b;
}
template<class T>
void biggest<T>::display()
{
cout<<"Biggest="<<max(a,b)<<endl;
}
void main()
{
clrscr();
biggest <int> intobj;
biggest <float> floatobj;
biggest <char> charobj;
cout<<"Biggest in Integer numbers:\n";
intobj.getdata();
intobj.display();
cout<<"Biggest in floating-point numbers:\n";
floatobj.getdata();
floatobj.display();
cout<<"Biggest in character:\n";
charobj.getdata();
charobj.display();
getch();
}
Output:
Biggest in Integer numbers:
Enter two numbers or characters:
4
6
Biggest=6
Biggest in floating-point numbers:
Enter two numbers or characters:
2.3
5.6
Biggest=5.6
Biggest in character:
Enter two numbers or characters:
d
f
Biggest=f
Friend declarations in class templates:
We know that the friend function is used to access private members of the
class. The same is implemented in the class template. There are three ways of
declaring friends.
- A non-template friend class or friend function.
- A bound friend class template or function template.
- An unbound friend class template or function template.
Let us take an example of a non-template friend or friend function.
class sum
{
private: void calculate();
};
template <class T>
class add
{
friend class combine;
friend void sum::calculate();
};
Here, the class combine should not be defined or declared in the global scope
before it is declared as friend in the class template add.
If we consider the second method of declaring the friend function in a class
template, there is one-to-one correspondence between the class template
sum’s instantiation and its friend.
template <class T>
class sum
{
private: void calculate();
}
template<class T>
class combine
{
// class definition
};
template <class T>
class add
{
friend class combine<T>;
friend void sum<T>::calculate();
};
Observe that the declaration or definition is made for the template before it is
used for declaring a friend within a class template.
In an unbound friend class template or function template method of declaring
the friend functions, there is also a one-to-one correspondence between the
class template sum’s instantiation and its friend. Observe the following
declaration.
template<class T>
class add
{
template<class T>
friend void sum<T>::calculate();
};
Nested class templates:
Similar to nested classes, class templates can also be enclosed one within
another. A nested class can be placed in either a private or public section of
an enclosing class template. When it is placed in the private section, it is not
accessible to the program. However it is accessible by enclosing the class
template and its friend.
Example:
template<class T>
class list
{
private: class node
{
T data;
node *ptr;
};
node *head, *temp;
public: //public members
};
Where class node is the nested class template while class list is the enclosing
class template. When a class list is instantiated, it generates its own node
class with the correct template argument for T. There is one-to-one
correspondence between the instantiation of the nested class template and its
enclosing class template.
Member templates: It is possible to write a function template or class
template as a member of normal class or member of a class template. Let us
take an example.
template<class T>
class example
{
private: // class member template
template <class U>
class integer_number
{
U data;
T value;
};
public: // function member template
template <class Type>
void sum(Type a, Type b)
{
Type c=a+b;
cout<<”c=”<<c;
}
};
Observe that, one private class member template and one public function
member template. Class member template integer_number has U and the
function member template sum has Type as template parameter. The
enclosing template integer_number has T as its template parameter. This can
be used inside the nested templates. Thus, the declaration
T value;
In the class member template integer_number.

EXERCISES
1. Define class template with its syntax and an example.
2. Write a program to find the sum of two numbers using a class
template.
3. What is class instantiation? Explain with a programming example.
4. Explain member functions of a class template with an example.
5. Describe how to declare a friend in class template declaration.
6. Briefly explain the nested class templates with an example.
7. Explain how to write member templates with an example.
CHAPTER 15
INHERITANCE
Introduction:
C++ classes can be used in several ways. This is done by creating new
classes, reusing the properties of existing one. It allows the user to create a
new class (derived class) from an existing class (base class). The derived
class inherits all the features from a base class and it can have additional
features of its own.
Definition: “Inheritance is the capability of one class to inherit properties
from another class”.
Inheritance is a process of acquiring properties from one class to another.
Base class: A class whose properties are inherited to another class is called
base class.
Derived class: A class whose properties are inherited from another class is
called derived class.
Advantages of Inheritance:
- Inheritance permit to reuse already existing code.
- Reduces development time.
- Easy to maintain.
- Easy to extend.
- Memory can be utilized properly.
If we do not use inheritance, then there are two disadvantages,
- Code written in the base class is to be repeated in the derived class that
leads to wastage of memory space.
- Testing to be done separately for both base and derived class that takes
a lot of time.
These problems can be solved using inheritance. If we reuse already existing
code in the base class then the above problems can be tackled.
In the below example, you can find a base class called Employee which
inherits properties to two other derived classes called supervisor and
manager that receives properties from the base class. These classes have
properties of base class in addition they have their own properties.

Levels of inheritance: There are five levels of inheritance. Viz.


- Single inheritance.
- Multilevel inheritance.
- Multiple inheritance.
- Hierarchical inheritance.
- Hybrid inheritance.
Single inheritance: if a class is derived from a single base class is called
single inheritance.

Defining the derived class: The syntax for defining the derived class is as
shown below.
class derived_class:visibility_mode base_class
{
// class body
};
Where, class is a keyword. derived_class is a valid identifier name of the
derived class and colon (:) shows the derivation from the base class.
visibility_mode specifies the type of derivation (private, public or protected).
base_class is a valid identifier name of base class.
The class body consists of properties of a base class and its own properties.
The base class must be terminated by a semicolon.
Visibility mode: The visibility mode (private, public and protected) in the
definition of derived class specifies whether the features of the base class are
privately derived or publicly derived or protected derived.
The following table shows the role of visibility mode,
Derived class
Base class
Public mode Private mode Protected mode
Private Not inherited Not inherited Not inherited
Public Public Private Protected
Protected Protected Private Protected

Private inheritance:
- The public members of the base class become the private members of
the derived class. They can be accessed by the member functions of the
derived class.
- The private members of the base class are not inherited by the derived
class.
- The protected members of the base class become private members to
the derived class.
/* Write a program to demonstrate the single inheritance in private
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:private father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata(); //accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display(); //accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Public inheritance:
- The public members of the base class become public to the derived
class.
- The private members of the base class cannot be inherited to the
derived class.
- The protected members of the base class stay protected in the derived
class.
/* Write a program to demonstrate the single inheritance in public
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:public father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata(); //accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display(); //accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Protected inheritance:
- The public members of the base class become protected in the derived
class.
- The protected members of the base class stay protected in the derived
class.
- The private members of the base class cannot be inherited to the
derived class.
/* Write a program to demonstrate the single inheritance in protected
mode. */
#include<iostream.h>
#include<conio.h>
class father
{
char name[20];
int age;
public: char complexion[10];
char gender;
void getdata();
void display();
};
class son:protected father
{
char qualification[10];
float salary;
public: void readdata();
void writedata();
};
void father::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the gender: ";
cin>>gender;
}
void father::display()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
cout<<"gender="<<gender<<endl;
}
void son::readdata()
{
father::getdata();
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void son::writedata()
{
father::display();
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the gender: m
Enter the qualification: MSc
Enter the salary: 100000
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
gender=m
Qualification=MSc
Salary=100000
Multilevel inheritance: The classes can also be derived from the classes
that are already derived is called multilevel inheritance.

// Write a program to demonstrate multilevel inheritance


#include<iostream.h>
#include<conio.h>
class grandfather
{
char name[20];
int age;
public: char complexion[10];
void getdata();
void putdata();
};
class father:public grandfather
{
char qualification[20];
float salary;
public: char complexion[10];
char gender;
void inputdata();
void outputdata();
};
class son:public father
{
char designation[20];
public: void readdata();
void writedata();
};
void grandfather::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
}
void grandfather::putdata()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
}
void father::inputdata()
{
grandfather::getdata(); // accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void father::outputdata()
{
grandfather::putdata(); // accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void son::readdata()
{
father::inputdata();
cout<<"Enter the designation: ";
cin>>designation;
}
void son::writedata()
{
father::outputdata();
cout<<"Designation="<<designation<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the qualification: MSc
Enter the salary: 100000
Enter the designation: Lecturer
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
Qualification=MSc
Salary=100000
Designation=Lecturer

Multiple inheritance: If a class is derived from more than one base class
is known as multiple inheritance.

// Write a program to demonstrate multiple inheritance


#include<iostream.h>
#include<conio.h>
class king
{
protected: char name[20];
int age;
public: float weight;
void getdata();
void putdata();
};
class queen
{
protected: char complexion[10];
float height;
public: void readdata();
void writedata();
};
class prince:public king, public queen
{
protected: char hobby[20];
public: void input();
void output();
};
void king::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the weight: ";
cin>>weight;
}
void king::putdata()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Weight="<<weight<<endl;
}
void queen::readdata()
{
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
cout<<"Enter the height: ";
cin>>height;
}
void queen::writedata()
{
cout<<"Complexion="<<complexion<<endl;
cout<<"height="<<height<<endl;
}
void prince::input()
{
king::getdata();
queen::readdata();
cout<<"Enter the hobby: ";
cin>>hobby;
}
void prince::output()
{
king::putdata();
queen::writedata();
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
prince p;
clrscr();
cout<<"Enter prince's information:\n";
p.input();
cout<<"Prince's Information is\n";
p.output();
getch();
}
Output:
Enter prince's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the weight: 73
Enter the complexion (fair, wheat or dark): wheat
Enter the height: 5.8
Enter the hobby: reading
Prince's Information is
Name=Hanumanth
Age=38
Weight=73
Complexion=wheat
height=5.8
Hobby=reading
Hierarchical inheritance: If a number of classes are derived from a
single base class is called hierarchical inheritance.

// Write a program to demonstrate hierarchical inheritance


#include<iostream.h>
#include<conio.h>
class staff
{
protected: char name[20];
int empid;
public: void getdata();
void putdata();
};
class manager:public staff
{
protected: float salary;
char designation[20];
public: void readdata();
void writedata();
};
class supervisor:public staff
{
protected: float salary;
char designation[20];
public: void input();
void output();
};
class clerk:public staff
{
protected: float salary;
char designation[20];
public: void receive();
void display();
};
void staff::getdata()
{
cout<<"Enter the employee id: ";
cin>>empid;
cout<<"Enter the name: ";
cin>>name;
}
void staff::putdata()
{
cout<<"Employee id="<<empid<<endl;
cout<<"Employee name="<<name<<endl;
}
void manager::readdata()
{
staff::getdata();
cout<<"Enter the designation: ";
cin>>designation;
cout<<"Enter the salary: ";
cin>>salary;
}
void manager::writedata()
{
staff::putdata();
cout<<"Designation="<<designation<<endl;
cout<<"Salary="<<salary<<endl;
}
void supervisor::input()
{
staff::getdata();
cout<<"Enter the designation: ";
cin>>designation;
cout<<"Enter the salary: ";
cin>>salary;
}
void supervisor::output()
{
staff::putdata();
cout<<"Designation="<<designation<<endl;
cout<<"Salary="<<salary<<endl;
}
void clerk::receive()
{
staff::getdata();
cout<<"Enter the designation: ";
cin>>designation;
cout<<"Enter the salary: ";
cin>>salary;
}
void clerk::display()
{
staff::putdata();
cout<<"Designation="<<designation<<endl;
cout<<"Salary="<<salary<<endl;
}
void main()
{
manager m;
supervisor s;
clerk c;
clrscr();
cout<<"Information of manager\n";
m.readdata();
cout<<"Information of supervisor\n";
s.input();
cout<<"Information of clerk\n";
c.receive();
cout<<"\n******Information of manager******\n";
m.writedata();
cout<<"\n******Information of supervisor******\n";
s.output();
cout<<"\n******Information of clerk******\n";
c.display();
getch();
}
Output:
Information of manager
Enter the employee id: 1
Enter the name: Hanumanth
Enter the designation: Manager
Enter the salary: 100000
Information of supervisor
Enter the employee id: 2
Enter the name: Swaroop
Enter the designation: Supervisor
Enter the salary: 50000
Information of clerk
Enter the employee id: 3
Enter the name: Raj
Enter the designation: Clerk
Enter the salary: 25000

******Information of manager******
Employee id=1
Employee name=Hanumanth
Designation=Manager
Salary=100000

******Information of supervisor******
Employee id=2
Employee name=Swaroop
Designation=Supervisor
Salary=50000

******Information of clerk******
Employee id=3
Employee name=Raj
Designation=Clerk
Salary=25000
Hybrid inheritance: Hybrid inheritance is a combination of hierarchical
and multiple inheritance.
/* Write a program to illustrate hybrid inheritance using multilevel-
multiple inheritance. */
#include<iostream.h>
#include<conio.h>
class grandfather
{
char name[20];
int age;
public: char complexion[10];
void getdata();
void putdata();
};
class father:public grandfather
{
char qualification[20];
float salary;
public: char complexion[10];
char gender;
void inputdata();
void outputdata();
};
class mother
{
char hobby[20];
public: void getting();
void putting();
};
class son:public father, public mother
{
char designation[20];
public: void readdata();
void writedata();
};
void grandfather::getdata()
{
cout<<"Enter the name: ";
cin>>name;
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the complexion (fair, wheat or dark): ";
cin>>complexion;
}
void grandfather::putdata()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Complexion="<<complexion<<endl;
}
void father::inputdata()
{
grandfather::getdata(); // accessible to the derived class
cout<<"Enter the qualification: ";
cin>>qualification;
cout<<"Enter the salary: ";
cin>>salary;
}
void father::outputdata()
{
grandfather::putdata(); // accessible to the derived class
cout<<"Qualification="<<qualification<<endl;
cout<<"Salary="<<salary<<endl;
}
void mother::getting()
{
cout<<"Enter the hobby: ";
cin>>hobby;
}
void mother::putting()
{
cout<<"Hobby="<<hobby<<endl;
}
void son::readdata()
{
father::inputdata();
mother::getting();
cout<<"Enter the designation: ";
cin>>designation;
}
void son::writedata()
{
father::outputdata();
mother::putting();
cout<<"Designation="<<designation<<endl;
}
void main()
{
son s;
clrscr();
cout<<"Enter son's information:\n";
s.readdata();
cout<<"Son's information is\n";
s.writedata();
getch();
}
Output:
Enter son's information:
Enter the name: Hanumanth
Enter the age: 38
Enter the complexion (fair, wheat or dark): wheat
Enter the qualification: MSc
Enter the salary: 100000
Enter the hobby: Cooking
Enter the designation: Lecturer
Son's information is
Name=Hanumanth
Age=38
Complexion=wheat
Qualification=MSc
Salary=100000
Hobby=Cooking
Designation=Lecturer
One more program can be written using hierarchical-multiple inheritance.
This is left to you to write the program on the same.
Virtual base classes: A situation where the program design would require
one base class call it A and two derived classes namely B and C, which are
inherited from the base class A. Furthermore, derived class D is created
from B and C. See the figure given below.
In the public inheritance, B and C inherit one copy of the base class data,
whereas derived class D inherited from B and C get two copies of the base
class data.
Suppose, a member function of D wants to access the data members of the
base class an ambiguity problem of which two copies is to access will be
encountered. The compiler will generate an error message for this
ambiguity. To overcome this problem, the derived class B and C should be
declared as virtual.
// Write a program to illustrate virtual base class
#include<iostream.h>
#include<conio.h>
class A
{
protected: int a;
public: void geta();
void puta();
};
class B:virtual public A
{
protected: int b;
public: void getb();
void putb();
};
class C: virtual public A
{
protected: int c;
public: void getc();
void putc();
};
class D:public B, public C
{
int sum;
public: void display();
};
void A::geta()
{
cout<<"Enter the value of a: ";
cin>>a;
}
void A::puta()
{
cout<<"a="<<a<<endl;
}

void B::getb()
{
cout<<"Enter the value of b: ";
cin>>b;
}
void B::putb()
{
cout<<"b="<<b<<endl;
}

void C::getc()
{
cout<<"Enter the value of c: ";
cin>>c;
}
void C::putc()
{
cout<<"c="<<c<<endl;
}
void D::display()
{
sum=a+b+c;
puta();
putb();
putc();
cout<<"\nSum="<<sum<<endl;
}
void main()
{
D d;
clrscr();
d.geta();
d.getb();
d.getc();
d.display();
getch();
}
Output:
Enter the value of a: 1
Enter the value of b: 2
Enter the value of c: 3
a=1
b=2
c=3

Sum=6
Abstract classes: It is a class that is not used to create objects. An abstract
class is defined only to act as a base class.
Constructors and destructors in derived classes:
When both the base and derived classes contain constructors, the base
class constructor is executed first and then the constructor in the derived
class is executed.
If the constructors are called down the line from the base to the derived
class, the destructors are called just in the reverse order. That is from the
derived class up to the base class.
/* Write a program to illustrate constructor and destructors in
derived classes. */
#include<iostream.h>
#include<conio.h>
class A
{
public: A()
{
cout<<"In base class constructor"<<endl;
}
~A()
{
cout<<"In base class destructor"<<endl;
}
};
class B:public A
{
public: B()
{
cout<<"In derived class constructor"<<endl;
}
~B()
{
cout<<"In derived class destructor"<<endl;
}
};
void main()
{
clrscr();
B obj;
getch();
}
Output:
In base class constructor
In derived class constructor
In derived class destructor
In base class destructor
Note: Trace this program to get the output as shown above. Otherwise,
only the first two statements will be displayed and the other two will not.
This is because before the statements are printed the destructor invokes.
Trace this program by pressing the F7 button (in Turbo C++ compiler) to
get the output as shown above.
EXERCISES
1. What is inheritance? Mention the access specifiers used in C++.
2. Explain single inheritance with a programming example.
3. Explain multilevel inheritance with a programming example.
4. Explain multiple inheritance with a programming example.
5. Explain hierarchical inheritance with a programming example.
6. Explain hybrid inheritance with a programming example.
7. What is a virtual base class? Explain with a programming example.
8. How do constructors and destructors invoke base and derived
classes? explain with a programming example.
CHAPTER 16
POLYMORPHISM AND VIRTUAL
FUNCTIONS
Introduction: In the previous lessons we have studied about some of the
features of OOP such as, data encapsulation, inheritance, polymorphism etc.
we are familiar with all of the features of OOPs but in this chapter, we will
learn still more about polymorphism.

Polymorphism can be achieved in two ways, one at the compile time and
another is at run-time. We have studied, implementation of compile time
polymorphism using function overloading and operator overloading. And the
run-time polymorphism is achieved using the virtual functions.

In order to achieve run-time polymorphism, we require the knowledge of


pointers to objects and pointers to derived classes.
Pointers to objects: As we have already studied, the pointer is a variable that
holds the address of other variables or objects. Pointers point to the objects
for a particular class.
// Write a program to illustrate the pointer to an object
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees;
}
void main()
{
student s,*sp;
sp=&s;
clrscr();
sp->read();
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Swaroop
enter the fees: 20000
register number=1
student name=Swaroop
student fees=20000
Note: There are two ways to access the member functions of a class. One is
using the dot(.) operator and the second is the arrow (->) operator. This arrow
access operator is used as a pointer to objects. In the above program observe
that, to access the function member read() and display() we have used object
sp followed by member access arrow (->) operator followed by member
function. the object pointer *sp must be initialized with the address of object
s, as shown below.
student s,*sp;
sp=&s;
Pointers to derived classes: A pointer declared for a base class can be used
for addressing the objects of the derived class. This is due to the type
compatibility of the pointer.
// Write a program to illustrate pointers to derived class
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees<<endl;
}
class student_friend:public student//single inheritance
{
int age;
char hobby[20];
public: void read();
void display();
};
void student_friend::read()
{
student::read();
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the hobby: ";
cin>>hobby;
}
void student_friend::display()
{
student::display();
cout<<"Age="<<age<<endl;
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
student s,*sp;
sp=&s;

student_friend sf;
clrscr();
sp->read();
sp->display();

sp=&sf;
sp->read();
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Swaroop
enter the fees: 15000
register number=1
student name=Swaroop
student fees=15000
enter the register number: 2
enter the student name: Raj
enter the fees: 12000
register number=2
student name=Raj
student fees=12000
Observe that, this program always shows the contents of the base class object
only. To display the contents of the derived class object, it is necessary to
type cast the pointer as shown in the following program.
/* Write a program to illustrate the type casting a pointer to objects in
single inheritance. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees<<endl;
}
class student_friend:public student//single inheritance
{
int age;
char hobby[20];
public: void read();
void display();
};
void student_friend::read()
{
student::read();
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the hobby: ";
cin>>hobby;
}
void student_friend::display()
{
student::display();
cout<<"Age="<<age<<endl;
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
student s,*sp;
sp=&s;

student_friend sf;
clrscr();
sp->read();
sp->display();
sp=&sf;
((student_friend *)sp)->read(); // pointer typecasting
((student_friend *)sp)->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Swaroop
enter the fees: 15000
register number=1
student name=Swaroop
student fees=15000
enter the register number: 2
enter the student name: Raj
enter the fees: 12000
Enter the age: 15
Enter the hobby: Walking
register number=2
student name=Raj
student fees=12000
Age=15
Hobby=Walking
Virtual functions: In the above program we have seen that the pointer to
object calls members of the base class. Addressing the appropriate object can
be done in two ways.
- Type Casting pointers
- Virtual functions.
We have come across type casting pointers, now we will learn about virtual
functions. The virtual function is used to achieve run-time polymorphism. A
member function of a class can be made virtual. The process of redefining a
virtual function in the derived classes is called function overriding.
Rules for writing virtual functions:
- The virtual functions must be defined in a base class.
- The virtual functions cannot be static members.
- The virtual functions can be declared as the friend functions to some
other class.
- The virtual functions should be declared in the public section of a
class.
- The prototype of the virtual functions must be the same in both base
and derived classes.
- A base class pointer can be used to address the derived class object.
But vice-versa is not true.
- No constructor is made as virtual, but the destructor can be made as
virtual.
Advantages of virtual functions:
- Virtual functions eliminate the necessity of typecasting the pointer to
access the member functions of the derived class object.
- The virtual function increases run-time efficiency.
/* Write a program to demonstrate virtual functions and the object to
pointer in achieving the run-time polymorphism. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: virtual void read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
virtual void display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees<<endl;
}
};
class student_friend:public student//single inheritance
{
int age;
char hobby[20];
public: void read();
void display();
};
void student_friend::read()
{
student::read();
cout<<"Enter the age: ";
cin>>age;
cout<<"Enter the hobby: ";
cin>>hobby;
}
void student_friend::display()
{
student::display();
cout<<"Age="<<age<<endl;
cout<<"Hobby="<<hobby<<endl;
}
void main()
{
student s,*sp;
sp=&s;

student_friend sf;
clrscr();
sp->read();
sp->display();

sp=&sf;
sp->read(); // pointer typecasting
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Priyanka
enter the fees: 10000
register number=1
student name=Priyanka
student fees=10000
enter the register number: 2
enter the student name: Sneha
enter the fees: 8000
Enter the age: 21
Enter the hobby: music
register number=2
student name=Sneha
student fees=8000
Age=21
Hobby=music
Pure virtual functions:
A virtual function which provides an interface for the derived class functions
to override but must not itself be invoked through the virtual mechanism is
called a pure virtual function.
Rules for writing pure virtual functions:
- A pure virtual function is a “do-nothing” member function.
- A pure virtual function can only be declared in the base class, not the
definition.
- A class having pure virtual functions cannot be used to instantiate
objects of its own.
The general form of declaring a pure virtual function,
virtual return_type function_name()=0;
// Write a program to illustrate a pure virtual function
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public: virtual void read()
{
cout<<"Enter the value of a: ";
cin>>a;
}
virtual void display()=0; // pure virtual function
};
class derived:public base
{
int b;
public: void read()
{
cout<<"Enter the value of b: ";
cin>>b;
}
void display()
{
cout<<"In derived class b="<<b<<endl;
}
};
void main()
{
clrscr();
base *bptr;
derived d;
bptr=&d;
bptr->read();
bptr->display();
getch();
}
Output:
Enter the value of b: 10
In derived class b=10
Virtual destructors:
We use virtual destructors when the objects in the derived class are created
dynamically using the new operator. the address of the derived class object
can be assigned to the pointer which points to the base class object. When we
want to delete the base pointer, it calls the base class destructor. In reality, the
derived class destructor must be called first and then the base class destructor.
To achieve this, we have to declare a virtual destructor in the base class.
// Write a program to illustrate the virtual destructor
#include<iostream.h>
#include<conio.h>
class base
{
int a;
public: base()
{
cout<<"Enter the value of a: ";
cin>>a;
}
virtual ~base()
{
cout<<"In the base class destructor a="<<a<<endl;
}
};
class derived:public base
{
int b;
public: derived()
{
cout<<"Enter the value of b: ";
cin>>b;
}
~derived()
{
cout<<"In the derived class destructor b="<<b<<endl;
}
};
void main()
{
clrscr();
base *bptr=new derived;
delete bptr;
getch();
}
Output:
Enter the value of a: 5
Enter the value of b: 10
In the derived class destructor b=10
In the base class destructor a=5

EXERCISES
1. What is run-time polymorphism? Classify polymorphism.
2. Describe pointers to objects with a programming example.
3. Write a program to demonstrate the pointer to derived classes.
4. How to do pointer typecasting? Explain with a programming
example.
5. What are virtual functions? Explain with an example.
6. State the rules for virtual functions.
7. Write the advantages of virtual functions.
8. What are pure virtual functions? Explain with an example.
9. How virtual destructors are used? Explain with suitable examples.
CHAPTER 17
FILE HANDLING
Introduction: We are familiar with cin and cout objects belonging to the
iostream class which are used to perform input and output operations. These
objects are used to accept input through the keyboard and display output on
to the monitor.
In C++, the input and output operations are sequences of flow of character
(bytes). An input and output stream are a flow of bytes from a device like a
keyboard, a disk drive or network connection etc. to main memory, called
input operation. If the bytes flow from main memory to a device like a
monitor, a printer, a disk drive or a network connection etc, is called output
operation.
Almost all computers utilize files, because files are used to store the
information permanently. Files are the basic storage for data. Word
processors create document files. Database programs create files of
information. Compilers and interpreters convert source programs into object
code files and executable files. A file itself is a bunch of bytes stored on
storage devices such as, magnetic tape, magnetic disk etc.
In C++, file input output operations can be performed using the header file
fstream.h. File input operations can be performed using istream.h and file
output operations can be performed using ostream.h.
The stream that supplies data to the program is known as input stream. It
reads the data from the file and hands it over to the program. The stream that
receives the data from the program is known as output stream. It writes the
received data to the file. These input output operations are depicted in the
following figure.
Stream class hierarchy for I/O operations:
All I/O operations can be performed by the stream classes that are derived
from two common base classes called ios and streambuf. The class ios is a
base class for the classes istream (an input stream), ostream (an output
stream) and iostream (an input-output stream). The following figure depicts
the stream class hierarchy for input output operations.

The three derived classes of ios, istream, ostream and fstream are used to
create an input stream, output stream and input-output stream.
Type of data files: We know that the files are used to store the data or
information permanently for future reference.
The data files are classified based on how data are stored and retrieved as,
- Text file
- Binary file
Text file:
- The information stored is in the form of Bits.
- No delimiters are used for a line.
- No translation required.
Binary file:
- The information stored is in the form of ASCII characters.
- Each line of text is terminated with a special character known as EOL
(End Of Line) character.
- Internal translation occurs.
Opening and closing files:
To create an input stream, you must declare the stream to be of class ifstream.
To create an output stream, you must declare the stream to be of class
ofstream. Streams that will be performing both input and output operations
must be declared as class fstream.
Opening a file can be accomplished in two ways:
- Opening file using constructor.
- Opening file using open() member function
Opening a file using constructor:
Syntax of opening a file for output only,
ofstream ofstream_object(“File_name”);
Example: ofstream fout(“text.dat”);
Where, fout is declared to be an object of ofstream type and it opens the
file text.dat in output purpose only.
Syntax of opening a file for input only,
ifstream ifstream_object(“file_name”);
Example: ifstream fin(“text.dat”);
Where, fin is declared to be an object of ifstream type and it opens the file
text.dat in input purpose only.
Opening a file using open():
Syntax of opening a file for output only,
ofstream_object.open(“file_name”) ;
Example: ofstream ofile;
ofile.open(“text.dat”);
Syntax of opening a file for input only,
ifstream_object.open(“file_name”);
Example: ifstream ifile;
ifile.open(“text.dat”);
if we have to open a file for both input and output operations, we use objects
of fstream class.
the syntax for opening a file an object of fstream class and the constructor is
as follows:
fstream fstream_object(“filename”,mode)
the syntax for opening a file an object of type fstream class and the open()
member function is as follows:
fstream_object.open(“filename”,mode)
The following table describes the type of file modes.
Mode Explanation
ios :: in Open a file for reading.
ios :: out Open a file for writing.
ios :: app Appends data to the end of the file.
File pointer moves to the end of the file but allows
ios :: ate writing data in any location in the file.

ios::binary Opening a binary file.


ios::noreplace Turn down opening if the file already exists.
ios::nocreate Turn down opening if the file does not exist.
ios::trunc On opening, delete the contents of the file.
Example:
fstream fout(“text.dat”,ios::out); // this opens a file in output mode
fstream fin(“text.dat”,ios::in); // this opens a file in input mode
We open the file sample.bin in binary mode to append data in output mode.
fstream file;
file.open(“sample.bin”,ios::out | ios::app | ios::binary);
The modes can be combined using bitwise OR (|) operator.
Closing file: After the intended operations are performed with the file, the
file should be saved on the secondary storage for future use. This is done by
the member function close(). The function close() removes the linkage
between the file and the stream object.
Syntax:
stream_object.close();
example:
fout.close();
fin.close();
// Write a program to demonstrate writing text onto the file
#include<fstream.h>
#include<conio.h>
void main()
{
ofstream fout;
fout.open("text.txt");
char s[20]="Hi there!";
fout<<s;
fout.close();
getch();
}
Output of this program is, it creates a file called text.txt and writes the text Hi
there! Into it as shown below.

Input and output operation in text files:


The text files need the following type of input output operations.
- put() function
- get() function
put() function: This function belongs to the class ofstream and writes a
single character.
Syntax:
ofstream_object.put(ch);
where, ofstream_object is an object of ofstream class and ch is a variable of
type char.
Example:
char ch=’h’;
ofstream fout(“text.txt”);
fout.put(ch);
Here, it writes the character stored in the variable ch.
get() function: This function belongs to the class ifstream and reads a single
character.
Syntax:
ifstream_object.get(ch);
where, ifstream_object is an object of ifstream class and ch is a variable of
type char.
Example:
char ch=’h’;
ifstream fin(“text.txt”);
fin.get(ch);
Here, it reads the character stored in the variable ch.
The getline() function: This function is used to read a whole line of text. It
belongs to the ifstream class.
Syntax:
fin.getline(buffer,SIZE);
Example:
char name[SIZE];
fstream fin;
fin.getline(name,SIZE);
Input and output operations in binary files: The binary files are used when
we create databases consisting of records. Usually records are the collection
of heterogeneous data. The binary file helps optimize storage space and file
I/O would be faster when compared to text files. The binary file uses the
following functions to perform input and output operations.
- write() member function
- read() member function
write() member function: This member function belongs to the ofstream
class. It is used to write binary data to a file.
Syntax:
fout.write((char *)&variable,sizeof(variable));
Where, fout is an object of type ofstream. The function takes two arguments,
the first argument is the address of the variable, the contents of which are
written to the file and the second argument is the size of the variable. The
address of the variable is type casted to pointer to char type. This is because
the write function does not bother to know the type of variable. It requires
data in terms of only bytes.
Example:
student s;
ofstream fout(“std.dat”,ios::binary);
fout.write((char *)&s,sizeof(s));
Where, it writes the contents of the object s to the file std.dat.
read() member function: This member function belongs to ifstream class. It
is used to write binary data to a file.
Syntax:
fin.read((char *)&variable,sizeof(variable));
Where, fin is an object of type ifstream. The function takes two arguments,
the first argument is the address of the variable, the contents of which are
read from the file and the second argument is the size of the variable. The
address of the variable is type casted to pointer to char type. This is because
the read function does not bother to know the type of variable. It requires data
in terms of only bytes.
Example:
student s;
ifstream fin(“std.dat”,ios::binary);
fin.read((char *)&s,sizeof(s));
Where, it reads the contents of the object s to the file std.dat.
Detecting end of file: While reading the contents of the file, the operation
should not cross the end of file. The ios class provides a member function
called eof(), which helps in detecting the end of a file. Once the end of the
file is detected with the use of the eof() function, we can stop reading further.
The member function eof() returns true if the end of file is encountered while
reading; otherwise it returns false.
Syntax:
if(fin.eof())
{
Statements;
}
This is used to execute a set of statements on reaching the end of the file
represented by the object fin.
while(!fin.eof())
{
Statements;
}
This is used to execute a set of statements as long as the end of the file is not
reached.
// Write a program to read the content of the file
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
ifstream fin;
fin.open("text.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
}
Output:
Hi there!
The output of the program is the text written in the file text.txt. In the last
program we had written Hi there! In the text.txt file hence, the same is
displayed here as an output.
File pointers and their manipulation: In C++, the file input output
operations are associated with the two file pointers, known as get pointer and
the put pointer. These pointers are useful in traversing the opened file while
reading or writing. The get pointer belongs to ifstream class and put pointer
belongs to ofstream class.
There are three modes to open a file:
- read only mode
- write only mode
- append mode
When a file is opened in a read only mode, the get pointer is automatically set
to the very first byte (0th byte) of the file. This helps to read the file content
from the beginning. Similarly, when a file is opened in a write mode, the
content of the file is erased (if it exists) and the put pointer is set to the first
byte of the file, so that we can write data from the beginning. In some
situations, it would be necessary for us to add new data to the existing file. In
this case we have to open the file in append mode. When a file is opened in
an append mode, the put pointer moves to the end of the file, so that we write
new data from that position. These internal stream pointers that point to the
reading or writing locations within a stream can be manipulated using the
following member function:
- seekg()
- seekp()
- tellg()
- tellp()
seekg(): This moves the get pointer to a specified location from the
beginning of a file. There are two types:
- seekg(long);
- seekg(offset,seekdir);
Where, the seekg(long) moves the get pointer to a specified location from the
beginning of a file.
The seekg(offset,seekdir) has two arguments. The offset indicates the number
of bytes the get pointer is to be moved from seekdir position.
Example 1: obj.seekg(10);
The above example tells that the get pointer points to the 10th byte in a file
from 0th byte.
The seekdir takes one of the following three direction constants.
Constant Meaning
ios::beg Offset specified from the beginning of the file.
ios::cur Offset specified from the current position of the get
pointer.
Example 2: obj.seekg(0,ios::beg);
This example makes the get pointer to move to the 0th byte.
obj.seekg(10,ios::beg);
This example makes the get pointer move to the 10th byte. (from the current
position of the file in forward direction).
obj.seekg(-10,ios::beg);
This example tells that the get pointer points to the 10th byte from the end of
the file in backward direction.
seekp(): This makes the put pointer to move to a specified location from the
beginning of a file.
- seekp(long);
- seekp(offset,seekdir);
The seekp(long) moves the put pointer to a specified location from the
beginning of a file.
In seekp(offset,seekdir) the offset indicates the number of bytes the put
pointer is to be moved from seekdir position. seekdir takes one of the three
seek direction constants as shown in the table given above.
Example: obj.seekp(0,ios::beg);
This example makes put pointer move to the 0th byte for writing.
obj.seekp(10,ios::beg);
This example makes the put pointer move to the 10th byte from the current
position of the file in forward direction for writing.
obj.seekp(-10,ios::beg);
This example makes the put pointer move to the 10th byte from the end of file
in backward direction.
tellg() member function: This member function belongs to ifstream class.
This function returns the current position of the get pointer.
Example: int position;
position=fin.tellg();
/* Write a program to find the location of the get pointer using tellg()
member function. */
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
ifstream fin;
fin.open("text.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
int position=fin.tellg();
cout<<"\nThe position of get pointer is "<<position;
fin.close();
getch();
}
Output:
Hi there!
The position of get pointer is 9
tellp() member function: This member function belongs to the ofstream
class. This function returns the current position of the put pointer.
Example: int position;
position=fout.tellp();
/* Write a program to find the location of the put pointer using tellp()
member function. */
#include<fstream.h>
#include<conio.h>
void main()
{
clrscr();
ofstream fout;
fout.open("text.txt");
char s[20]="Hi there!";
fout<<s;
int position=fout.tellp();
cout<<"\nThe position of the put pointer is "<<position;
fout.close();
getch();
}
Output:
The position of the put pointer is 9
Basic operations on binary file in C++:
- Searching: The process of finding the position of a data item is called
searching.
- Appending data: The process of combining data at the end of the
current data is called appending data.
- Inserting data in sorted files: The process of adding data items in the
respective positions specified.
- Deleting a record: The process of removal of record(s) from the file
is called deleting a record.
- Modifying data: The process of changing the data as per the
requirements is called modifying data.
EXERCISES
1. What are input and output operations? Explain with a neat
labelled diagram.
2. Explain the hierarchy of classes to perform I/O operations.
3. Describe the types of data files.
4. Explain the methods of opening and closing a file with examples.
5. How to perform input and output operation in text files.
6. Explain about input and output operations in binary files.
7. How to detect the end of a file? Explain with a programming
example.
8. Briefly describe about file pointers and their manipulation.
LAB ASSIGNMENTS
/*1. Write a program to find the frequency of presence of an element in
an array*/
#include<iostream.h>
#include<conio.h>
class frequency
{
int a[10],n,i,ele;
public: void getdata();
void putdata();
};
void frequency::getdata()
{
cout<<"Enter the size of an array: ";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
cin>>a[i];
}
void frequency::putdata()
{
int count=0;
cout<<"Enter the element whose frequency is to be checked: ";
cin>>ele;
for(i=0;i<n;i++)
if(ele==a[i])
count++;
cout<<ele<<" has appeared "<<count<<" times";
}
void main()
{
frequency f;
clrscr();
f.getdata();
f.putdata();
getch();
}
Output:

run 1:
Enter the size of an array: 5
Enter the elements
1
1
1
2
3
Enter the element whose frequency is to be checked: 1
1 has appeared 3 times

run 2:
Enter the size of an array: 5
Enter the elements
1
2
3
4
5
Enter the element whose frequency is to be checked: 6
6 has appeared 0 times

/* 2. Write a program to create a class with data member principal, time


and rate. Create member functions to accept data values to compute
simple interest and to display the result*/
#include<iostream.h>
#include<conio.h>
class SI
{
int time;
float principal,rate;
public: void getdata()
{
cout<<"Enter the principal, time and rate of interest: \n";
cin>>principal>>time>>rate;
}
float compute_si()
{
return(principal*time*rate/100.0);
}
void display()
{
cout<<"Simple Interest="<<compute_si();
}
};
void main()
{
SI s;
clrscr();
s.getdata();
s.display();
getch();
}
Output:
Enter the principal, time and rate of interest:
1000
2
5
Simple Interest=100
/* 3. Write a program to create a class with data members a, b, c and
member
functions to input data, compute the discriminant based on the following
conditions and print the roots.
- if discriminant=0, print the roots that are equal
- if the discriminant is>0, print the real roots
- if the discriminant is<0, print that the roots are imaginary*/

#include<iostream.h>
#include<conio.h>
#include<math.h>
class quad
{
float x1,x2,imaginarypart,realpart,discriminant,a,b,c;
public: void getdata()
{
cout<<"Enter the values of a, b, c: ";
cin>>a>>b>>c;
discriminant=b*b-4*a*c;
}
void putdata()
{
if(discriminant>0)
{
x1=(-b+sqrt(discriminant))/(2*a);
x2=(-b-sqrt(discriminant))/(2*a);
cout<<"Roots are real and different:\n";
cout<<"x1="<<x1<<" and x2="<<x2;
}
else if(discriminant==0)
{
x1=-b/(2*a);
cout<<"Roots are real and equal\n";
cout<<"x1=x2="<<x1;
}
else
{
realpart=-b/(2*a);
imaginarypart=sqrt(-discriminant)/(2*a);
cout<<"Roots are imaginary\n";
cout<<realpart<<"+"<<imaginarypart<<"i"<<endl;
cout<<realpart<<"-"<<imaginarypart<<"i";
}
}
};
void main()
{
quad q;
clrscr();
q.getdata();
q.putdata();
getch();
}
Output:

run 1:
Enter the values of a, b, c: 1
2
2
Roots are imaginary
-1+1i
-1-1i

run 2:
Enter the values of a, b, c: 1
4
4
Roots are real and equal
x1=x2=-2

run 3:
Enter the values of a, b, c: 1
5
6
Roots are real and different:
x1=-2 and x2=-3
/* 4. Program to find the area of a square/rectangle/triangle using
function overloading. */
#include<iostream.h>
#include<conio.h>
class function_overloading
{
public: int area(int a) // area of a square
{
return(a*a);
}
int area(int l,int w) // area of a rectangle
{
return(l*w);
}
double area(double b,double h)
{
return(0.5*b*h);
}
};
void main()
{
function_overloading f;
clrscr();
cout<<"Area of square="<<f.area(5)<<endl;
cout<<"Area of rectangle="<<f.area(5,10)<<endl;
cout<<"Area of triangle="<<f.area(2.0,3.0);
getch();
}
Output:
Area of square=25
Area of rectangle=50
Area of triangle=3
// 5. Program to find the cube of a number using inline functions.
#include<iostream.h>
#include<conio.h>
inline int cube(int a)
{
return(a*a*a);
}
void main()
{
int x,y;
clrscr();
x=cube(5);
cout<<"Cube of 5="<<x<<endl;
y=cube(10);
cout<<"Cube of 10="<<y;
getch();
}
Output:
Cube of 5=125
Cube of 10=1000
/* 6. Write a program to find the sum of the series 1+x+x^2+...+x^n
using constructors. */
#include<iostream.h>
#include<conio.h>
class series
{
int x,n;
public: series(int x1,int n1)
{
x=x1;
n=n1;
}
void display();
};
void series::display()
{
int sum=1;
for(int i=0;i<n;i++)
{
sum=sum*x;
sum=sum+1;
}
cout<<"Sum of the series 1+x+x^2+...+x^n="<<sum;
}
void main()
{
int x1,n1;
clrscr();
cout<<"Enter the value of x: ";
cin>>x1;
cout<<"Enter the value of n: ";
cin>>n1;
series s(x1,n1);
s.display();
getch();
}
Output:
Enter the value of x: 2
Enter the value of n: 3
Sum of the series
1+x+x^2+...+x^n=15
/* 7. Create a base class containing the data members roll number and
name. Also create a member function to read and display the data using
the concept of single level inheritance. Create a derived class that
contains marks of two subjects and total marks as the data members. */
#include<iostream.h>
#include<conio.h>
class abc
{
int rollno;
char name[20];
public:
void read()
{
cout<<"enter roll no and name"<<endl;
cin>>rollno>>name;
}
void display()
{
cout<<"roll no:"<<rollno<<endl;
cout<<"name:"<<name<<endl;
}
};
class xyz:public abc
{
int m1;
int m2;
int t;
public:
void read1()
{
cout<<"enter the first marks & second marks:";
cin>>m1>>m2;
t=m1+m2;
}
void display1()
{
cout<<"first marks="<<m1<<endl;
cout<<"second marks="<<m2<<endl;
cout<<"total marks="<<t<<endl;
}
};
void main()
{
xyz ob;
clrscr();
ob.read();
ob.read1();
ob.display();
ob.display1();
getch();
}
Output:
enter roll no and name
1
Sonia
enter the first marks & second marks:67
77
roll no:1
name:Sonia
first marks=67
second marks=77
total marks=144
/* 8. Create a class containing the following data members register No.,
name and fees. Also create a member function to read and display the
data using the concept of pointers to objects. */
#include<iostream.h>
#include<conio.h>
class student
{
int regno;
char name[20];
float fees;
public: void read();
void display();
};
void student::read()
{
cout<<"enter the register number: ";
cin>>regno;
cout<<"enter the student name: ";
cin>>name;
cout<<"enter the fees: ";
cin>>fees;
}
void student::display()
{
cout<<"register number="<<regno<<endl;
cout<<"student name="<<name<<endl;
cout<<"student fees="<<fees;
}
void main()
{
student s,*sp;
sp=&s;
clrscr();
sp->read();
sp->display();
getch();
}
Output:
enter the register number: 1
enter the student name: Rakshita
enter the fees: 1000
register number=1
student name=Rakshita
student fees=1000
// 9. Write a program to demonstrate hierarchical inheritance.
#include<iostream.h>
#include<conio.h>
class book
{
protected: char book_title[20];
char author_name[20];
float price;
public: void getdata();
void putdata();
};
class textbook:public book
{
protected: int pages;
int stock;
public: void getdata();
void putdata();
};
class comicbook:public book
{
protected: int pages;
int stock;
public: void getdata();
void putdata();
};
void book::getdata()
{
cout<<"Enter the book title: " ;
cin>>book_title;
cout<<"Enter the name of the author: ";
cin>>author_name;
cout<<"Enter the price of the book: ";
cin>>price;
}
void book::putdata()
{
cout<<"Book title: "<<book_title<<endl;
cout<<"Author name: "<<author_name<<endl;
cout<<"Price :"<<price<<endl;
}
void textbook::getdata()
{
book::getdata();
cout<<"Enter the number of pages: ";
cin>>pages;
cout<<"Enter the stock: ";
cin>>stock;
}
void textbook::putdata()
{
book::putdata();
cout<<"Number of pages: "<<pages<<endl;
cout<<"Number of books in stock: "<<stock<<endl;
}
void comicbook::getdata()
{
book::getdata();
cout<<"Enter the number of pages: ";
cin>>pages;
cout<<"Enter the stock: ";
cin>>stock;
}
void comicbook::putdata()
{
book::putdata();
cout<<"Number of pages: "<<pages<<endl;
cout<<"Number of books in stock: "<<stock<<endl;
}
void main()
{
textbook tb;
comicbook cb;
clrscr();
cout<<"Details of text book:\n";
tb.getdata();
cout<<"Details of comic book:\n";
cb.getdata();
cout<<"\n***** Information of text book *****\n";
tb.putdata();
cout<<"\n***** Information of comic book *****\n";
cb.putdata();
getch();
}
Output:
Enter the name of the author: Hanumanth
Enter the price of the book: 600
Enter the number of pages: 330
Enter the stock: 1000
Details of comic book:
Enter the book title: Chanakya
Enter the name of the author: Priyanka
Enter the price of the book: 230
Enter the number of pages: 230
Enter the stock: 500

***** Information of text book *****


Book title: C++
Author name: Hanumanth
Price :600
Number of pages: 330
Number of books in stock: 1000

***** Information of comic book *****


Book title: Chanakya
Author name: Priyanka
Price :230
Number of pages: 230
Number of books in stock: 500
// 10. Write a C++ program to find the sum of two compatible matrices.
#include<iostream.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],s[5][5],i,j,r1,c1,r2,c2;
clrscr();
cout<<"Enter the order of the first matrix:\n";
cin>>r1>>c1;
cout<<"Enter the order of the second matrix:\n";
cin>>r2>>c2;
if((r1==r2)&&(c1==c2))
{
cout<<"Enter the elements of the first matrix:\n";
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
cin>>a[i][j];

cout<<"Enter the elements of the second matrix:\n";


for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
cin>>b[i][j];

for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
s[i][j]=a[i][j]+b[i][j];

cout<<"The resultant matrix is:\n";


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
cout<<s[i][j]<<"\t";
cout<<endl;
}
}
else
cout<<"Matrices are not compatible"<<endl;
getch();
}
Output:
Enter the order of the first matrix:
2
2
Enter the order of the second matrix:
2
2
Enter the elements of the first matrix:
12
34
Enter the elements of the second matrix:
56
78
The resultant matrix is:
6 8
10 12

You might also like