0% found this document useful (0 votes)
294 views270 pages

Unit 1-5

This document provides an introduction to programming using C++. It discusses object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It also covers basic C++ concepts such as data types, variables, constants, operators, expressions, type casting, functions and input/output statements. The document is divided into five units that cover topics ranging from introduction to OOP to classes and objects in C++. It aims to teach readers the fundamentals of programming in C++.

Uploaded by

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

Unit 1-5

This document provides an introduction to programming using C++. It discusses object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It also covers basic C++ concepts such as data types, variables, constants, operators, expressions, type casting, functions and input/output statements. The document is divided into five units that cover topics ranging from introduction to OOP to classes and objects in C++. It aims to teach readers the fundamentals of programming in C++.

Uploaded by

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

INTRODUCTION TO

PROGRAMMING
USING C++

INTRODUCTION TO PROGRAMMING USING C++


B.A. (PROGRAMME) IN COMPUTER SCIENCE DISCIPLINE
PAPER-II DISCIPLINE-A1/ PAPER-III DISCIPLINE-B1
SEMESTER-I
(MINOR PAPER-II)

DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION
UNIVERSITY OF DELHI UNIVERSITY OF DELHI
Introduction to Programming Using C++

Editors
Prof. Ajay Jaiswal

Content Writers
Dr. Deepali Bajaj, Seema
Dr. Anuradha Singhal
.
Academic Coordinator
Mr. Deekshant Awasthi

© Department of Distance and Continuing Education


ISBN: 978-81-19169-94-8
Ist edition: 2023
E-mail: [email protected]
[email protected]

Published by:
Department of Distance and Continuing Education
Campus of Open Learning/School of Open Learning,
University of Delhi, Delhi-110 007

Printed by:
School of Open Learning, University of Delhi

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

This Study Material is duly recommended in the meeting of Standing Committee


held on 08/05/2023 and approved in Academic Council meeting held on 26/05/2023
Vide item no. 1014 and subsequently Executive Council Meeting held on
09/06/2023 vide item no. 14 {14-1(14-1-11)}

Corrections/Modifications/Suggestions proposed by Statutory Body,


DU/Stakeholder/s in the Self Learning Material (SLM) will be incorporated in
the next edition. However, these corrections/modifications/suggestions will be
uploaded on the website https://sol.du.ac.in. Any feedback or suggestions can be
sent to the email- [email protected]

Printed at: Vikas Publishing House Pvt. Ltd. Plot 20/4, Site-IV, Industrial Area Sahibabad, Ghaziabad - 201 010 (1200 Copies)

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

SYLLABUS
Introduction to Programming Using C++
Syllabus Mapping

Unit - 1: Introduction to C++


Need and characteristics of Object-Oriented Programming, Structure of a Lesson-1: Introduction to OOP
C++ Program (main () function, header files, output, input, comments), compile Lesson-2: Introduction and
and execute a simple program. Basic Concepts of C++
(Pages 3-44)

Unit - 2: Data types and Expressions


Keywords, built in data types, variables and constants, naming convention, Lesson-3: Operators,
Input-Output statements, operators and their precedence, expressions, Expressions, Type Casting
typecasting, library functions. (Pages 47-81)

Unit - 3: Control Constructs in C++


Decision making using selection constructs, iteration using looping Lesson-4: Decision Control
constructs. Statements in C++
Lesson-5: Loops in C++
(Pages 85-140)

Unit - 4: Arrays, Pointers and User Defined Functions


Defining and initializing single and multi-dimensional arrays, user defined Lesson-6: Functions in C++
functions, passing arguments to functions, returning values from functions, Lesson-7: Arrays and
inline functions, default arguments, introduction to pointers. Pointers in C++
(Pages 143-202)

Unit - 5: Classes and Objects


Need and implementation of abstraction, encapsulation, inheritance and Lesson-8: Classes and
polymorphism, creating classes, objects as function arguments, modifiers Objects in C++
and access control, constructors and destructors. (Pages 205-255)

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

CONTENTS

UNIT I: INTRODUCTION TO OOP

Lesson 1 Introduction to OOP 3–23


1.1 Learning Objectives
1.2 What is Programming
1.3 Translator Program
1.3.1 Three Types of Translator Programs
1.4 Procedure-Oriented Programming
1.4.1 Characteristics of Procedure-Oriented Programming
1.5 Object-Oriented Programming (OOP)
1.5.1 Introduction
1.5.2 OOP Definition
1.5.3 Benefits of OOP
1.5.4 Why is OOP popular?
1.6 Characteristics of OOP
1.6.1 Class
1.6.2 Object
1.6.3 Data Abstraction
1.6.4 Encapsulation
1.6.5 Inheritance
1.6.6 Polymorphism
1.6.7 Dynamic Binding
1.6.8 Message Passing
1.7 Need of OOP
1.8 Difference between Procedure-Oriented Programming and OOP

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

1.9 Summary
1.10 Glossary
1.11 Answers to In-Text Questions
1.12 Self-Assessment Questions
1.13 References
1.14 Suggested Reading

Lesson 2 Introduction and Basic Concepts of C++ 25–44


2.1 Learning Objectives
2.2 Introduction to C++
2.2.1 Features of C++
2.3 Basic Terminology of C++
2.3.1 Tokens
2.3.2 C++ Keywords
2.3.3 Identifiers
2.3.4 Variable
2.3.5 Constants
2.4 Data Types
2.4.1 Built-in Data Types in C++
2.4.2 Derived Data Types in C++
2.4.3 Abstract or User-Defined Data Types in C++
2.5 Structure of C++ Program
2.5.1 Comments
2.5.2 Naming Convention
2.5.3 Main Function
2.5.4 Input Output Statements
2.6 Summary

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

2.7 Glossary
2.8 Answers to In-Text Questions
2.9 Self-Assessment Questions
2.10 References
2.11 Suggested Reading

UNIT II: DATA TYPES AND EXPRESSIONS

Lesson 3 Operators, Expressions, Type Casting 47–81


3.1 Learning Objectives
3.2 Arithmetic Operators
3.3 Assignment Operators
3.4 Relational Operators
3.5 Logical Operators
3.6 Bitwise Operators
3.7 Operators and their Precedence
3.8 Expressions
3.9 Typecasting in C++
3.9.1 Implicit Conversion
3.9.2 Explicit Conversion
3.10 Library Functions
3.11 Header Files and Library Files
3.11.1 Header Files
3.11.2 Library Files
3.12 #include Usage
3.12.1 System/Library Header Files
3.12.2 User-Defined Header Files

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

3.13 Solved Exercise


3.14 Summary
3.15 Glossary
3.16 Answers to In-Text Questions
3.17 Self-Assessment Questions
3.18 References
3.19 Suggested Readings

UNIT III: CONTROL CONSTRUCTS IN C++

Lesson 4 Decision Control Statements in C++ 85–106


4.1 Learning Objectives
4.2 Introduction
4.3 if Statement
4.4 if-else Statement
4.5 Nested if Statement
4.6 if-else-if Ladder
4.7 switch Statement
4.8 Conditional Operator
4.9 Summary
4.10 Glossary
4.11 Answers to In-Text Questions
4.12 Self-Assessment Questions
4.13 References
4.14 Suggested Readings

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

Lesson 5 Loops in C++ 107–140


5.1 Learning Objectives
5.2 Introduction
5.3 for Loop
5.4 while Loop
5.5 do while Loop
5.6 Jump Statements
5.6.1 break
5.6.2 continue
5.6.3 goto
5.6.4 return
5.7 Summary
5.8 Glossary
5.9 Answers to In-Text Questions
5.10 Self-Assessment Questions
5.11 References
5.12 Suggested Readings

UNIT IV: ARRAYS, POINTERS AND USER


DEFINED FUNCTIONS
Lesson 6 Functions in C++ 143–172
6.1 Learning Objectives
6.2 Introduction
6.3 Uses of Functions
6.4 Types of Functions
6.4.1 Built-in Functions
6.4.2 User Defined Functions

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

6.5 Call Methods in Function


6.6 Function Overloading
6.7 Default Arguments
6.7.1 Ambiguity in Function Overloading When Done Using Default Arguments
6.8 Return by Reference
6.9 Solved Exercise
6.10 Summary
6.11 Glossary
6.12 Answers to In-Text Questions
6.13 Self-Assessment Questions
6.14 References
6.15 Suggested Readings
Lesson 7 Arrays and Pointers in C++ 173–202
7.1 Learning Objectives
7.2 Introduction of Arrays
7.3 Initialization and Declaration of Array
7.3.1 Initializing Values to Array during Declaration
7.3.2 Assigning Values to Array after Declaration
7.4 Types of Array in C++
7.4.1 Single Dimensional Array
7.4.2 Multi-Dimensional Array
7.5 Passing Array to Function
7.6 Pointers
7.7 Pointer- Declaration and Initialization
7.8 Solved Exercise

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

7.9 Summary
7.10 Glossary
7.11 Answers to In-Text Questions
7.12 Self-Assessment Questions
7.13 References
7.14 Suggested Readings

UNIT V: CLASSES AND OBJECTS

Lesson 8 Classes and Objects in C++ 205–255


8.1 Learning Objectives
8.2 Introduction to Classes
8.3 Classes and Objects
8.4 Advantages of Objects and Classes in C++
8.5 Member Function in Classes
8.5.1 Inside Class
8.5.2 Outside Class
8.6 Constructors in C++
8.7 Destructors in C++
8.8 Objects as Arguments
8.9 Returning Objects from Functions
8.10 Inheritance in C++
8.10.1 Access Modes in Inheritance
8.11 Types of Inheritance
8.11.1 Single Inheritance
8.11.2 Multiple Inheritance
8.11.3 Multilevel Inheritance
8.11.4 Hierarchical Inheritance

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

8.12 Solved Exercise


8.13 Summary
8.14 Glossary
8.15 Answers to In-Text Questions
8.16 Self–Assessment Questions
8.17 References
8.18 Suggested Readings

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
UNIT I: INTRODUCTION TO OOP

LESSON 1 INTRODUCTION TO OOP

LESSON 2 INTRODUCTION AND BASIC CONCEPTS


OF C++
Introduction to OOP

LESSON 1 NOTES

INTRODUCTION TO OOP

Dr. Deepali Bajaj


Associate Professor
Shaheed Rajguru College of Applied Sciences for Women
University of Delhi
[email protected]
Seema
Assistant Professor
Shaheed Rajguru College of Applied Sciences for Women
University of Delhi
[email protected]
Structure
1.1 Learning Objectives
1.2 What is Programming
1.3 Translator Program
1.3.1 Three Types of Translator Programs
1.4 Procedure-Oriented Programming
1.4.1 Characteristics of Procedure-Oriented Programming
1.5 Object-Oriented Programming (OOP)
1.5.1 Introduction
1.5.2 OOP Definition
1.5.3 Benefits of OOP
1.5.4 Why is OOP popular?
1.6 Characteristics of OOP
1.6.1 Class
1.6.2 Object
1.6.3 Data Abstraction
1.6.4 Encapsulation
1.6.5 Inheritance
1.6.6 Polymorphism
1.6.7 Dynamic Binding
1.6.8 Message Passing
1.7 Need of OOP
Self-Instructional
1.8 Difference between Procedure-Oriented Programming and OOP Material 3

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 1.9 Summary


1.10 Glossary
1.11 Answers to In-Text Questions
1.12 Self-Assessment Questions
1.13 References
1.14 Suggested Reading

1.1 LEARNING OBJECTIVES

 To understand the concept of Programming Language


 To explain the overview of Translator Program
 To describe the concept of Procedure-Oriented Programming
 To discuss the concept of Object-Oriented programming
 To learn the OOP terminology, such as classes, objects, data abstraction and
encapsulation, inheritance and polymorphism
 To analyse the need and benefits of OOP

1.2 WHAT IS PROGRAMMING

A computer needs step-wise instructions to perform any action. The set of instructions
that tells the computer what to do is called a Program. The process of writing a program
in a computer language is called Programming. Each programming language has its
own specific rules. The evolution of programming has made it easier for programmers
to write and understand powerful application programs.
The evolution of programming languages can be categorized into several generations
or phases. Each generation represents advancements and new concepts introduced in
programming languages. Here is an overview of the different generations of
programming languages:
1. First Generation (Machine Language): The first programming languages
Self-Instructional
4 Material were machine languages, which directly corresponded to the binary instructions

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

understood by computers. They were difficult to write and understand, as they NOTES
involved low-level instructions specific to the computer architecture.
2. Second Generation (Assembly Language): Assembly languages provided
a more human-readable representation of machine language instructions. They
used mnemonic codes and symbols to represent the machine instructions, making
programming slightly more accessible.
3. Third Generation (Procedural Languages): The third generation brought
the concept of high-level programming languages, such as FORTRAN (1957),
COBOL (1959), and ALGOL (1958). These languages introduced concepts
like variables, loops, conditionals, and subroutines. They focused on algorithmic
and procedural programming and offered more abstraction from the underlying
machine.
4. Fourth Generation (Domain-Specific Languages): Fourth-generation
languages (4GL) were designed to address specific domains or problem areas.
They aimed to provide higher-level abstractions and simplify the programming
process for specific tasks like database management, report generation, and
data analysis. Examples of fourth-generation languages include SQL (Structured
Query Language) and MATLAB.
5. Fifth Generation (Logic Programming): The fifth generation involved the
development of logic programming languages, which focused on declarative
programming. Prolog (1972) is a notable example. These languages use formal
logic to specify problems and solutions, rather than traditional procedural or
imperative approaches. The introduction of Object-Oriented Programming
(OOP) languages, such as Smalltalk (1972) and C++ (1983), brought a
paradigm shift. OOP emphasizes organizing code around objects, encapsulation,
inheritance, and polymorphism. It enables modular, reusable, and extensible
code, making it easier to manage complex systems. Scripting languages like
Perl (1987), Python (1991), and Ruby (1995) gained popularity due to their
ease of use and rapid development capabilities. These languages are often
interpreted, allowing for dynamic and flexible programming. They excel in tasks
like web development, automation, and scripting.

Self-Instructional
Material 5

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
1.3 TRANSLATOR PROGRAM

As you know, a computer can understand only machine language, so programs written
in any other language have to be converted into machine language. The translator
program is used to convert source language programs into machine language programs.
A program written in a high-level language is called the source program or source
code whereas a program converted into machine language by a translator program is
called Object program or Object code as shown in Figure 1.1.

Source Code Translator Object Code

Fig. 1.1 Translator Program

1.3.1 Three Types of Translator Programs

A translator is a program that converts source code into machine code. Generally,
there are three types of translators: assemblers, interpreters, and compilers.
 Assembler: An assembler is a program that translates assembly language code
into machine code.
 Interpreter: An interpreter is a software program that translates source code
written in a high-level programming language into low-level language. It reads
the source code line by line, interprets each line, and executes the corresponding
instructions in real time.
 Compiler: A compiler is a program that translates source code written in a
high-level programming language into machine code. It translates the whole
program at once. It generates the object code for the program along with a list
of errors (if any). The execution speed of the compiler is faster as compared to
the interpreter.
The high-level programming languages are broadly categorized into two
categories:
(1) Procedure-Oriented programming (POP) language
Self-Instructional
6 Material (2) Object-Oriented programming (OOP) language

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

NOTES
1.4 PROCEDURE-ORIENTED PROGRAMMING

A procedure-oriented programming language, also known as procedural programming


language, is a type of programming language that follows a procedural programming
paradigm. In this paradigm, a program is structured around procedures or subroutines,
which are reusable blocks of code that perform specific tasks. Any given procedure
may be invoked at any time during the execution of a program, by other procedures,
or by itself.
The main focus of a procedure-oriented language is on procedures or functions
rather than data. The program’s flow of execution is determined by a sequence of
procedure calls, with each procedure containing a series of statements that manipulate
data. These procedures can take input parameters and return values, allowing for
modular and organized code.
Procedure-oriented languages typically provide constructs such as loops,
conditionals, and subroutines to control the flow of execution. Examples of popular
procedure-oriented languages include C, Pascal and FORTRAN.
In a procedure-oriented language, the emphasis is on breaking down a problem
into smaller sub-problems and solving each sub-problem with the help of a
corresponding procedure. Data is often manipulated using global variables that can be
accessed and modified by multiple procedures. While this approach can be
straightforward for smaller programs, it can become challenging to manage and maintain
as programs grow larger and more complex.

1.4.1 Characteristics of Procedure-Oriented Programming

The following points discuss the characteristics of Procedure-oriented programming:


1. Emphasis on Procedures: Procedure-oriented programming focuses on
organizing a program into a series of procedures or functions. Procedures are
self-contained blocks of code that perform specific tasks. The main program
calls these procedures to accomplish the desired functionality.
2. Top-down Design: The program structure is designed using a top-down
approach, where the problem is divided into smaller sub-problems, and Self-Instructional
procedures are created to solve each sub-problem. Material 7

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 3. Global Data: Procedure-oriented languages often use global data, which can
be accessed and modified by multiple procedures as shown in Figure 1.2. Global
data provides a way to share information between procedures, but it can make
the code more complex and harder to manage as the program grows.
4. Emphasis on Algorithms and Logic: Procedure-oriented programming focuses
on defining algorithms and logical steps to solve a problem. The code is typically
organized around sequences of statements, loops, and conditionals to control
the flow of execution.
5. Lack of Data Abstraction: Procedure-oriented languages often lack strong
mechanisms for data abstraction and encapsulation. Data and procedures are
treated separately, and there is less emphasis on Modelling real-world entities
as objects. This can make it harder to manage and reuse code in larger programs.
6. Procedural Flow: The program’s execution follows a linear and procedural
flow. Statements are executed one after another, and the flow can be altered
using control structures such as loops and conditionals.
7. Limited Code Reusability: In procedure-oriented programming, code
reusability is typically achieved by creating reusable procedures or functions.
However, the reuse is limited to the procedures themselves, and sharing data
between procedures can lead to code dependencies and potential issues.
8. Efficient Resource Utilization: Procedure-oriented languages are generally
optimised for memory and performance. These languages regulate system
resources at the hardware level.

Fig. 1.2 Data and Functions in Procedure-Oriented Programming


Self-Instructional
8 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

While procedure-oriented programming has its strengths, modern programming NOTES


paradigms, such as object-oriented programming and functional programming, have
gained popularity due to their ability to address the limitations of procedure-oriented
approaches in managing complexity, promoting code reusability, and enhancing
maintainability.

1.5 OBJECT-ORIENTED PROGRAMMING (OOP)

Here, we will study the meaning and benefits of using Object-Oriented programming
along with the reasons of its popularity.

1.5.1 Introduction

Object-Oriented Programming (OOP) is one of the most widely used approaches in


computer programming today. OOP is widely available to developers of all skill levels
and specialisations because it is supported by the vast majority of popular programming
languages. Over the past few years, OOP has seen an acceleration in popularity.
Companies that create software frequently issue “object-oriented” variants of their
wares.
Object-Oriented Programming (OOP) is a software design methodology that
concentrates on breaking down large programs into smaller and more manageable
objects. This facilitates enhanced program organisation and maintenance. Object-
orientation evolved from procedural programming. OOP enables applications to be
more flexible and extensible. It also encourages code reuse, which reduces development
expenses.
One of the primary advantages of object-oriented programming is that it facilitates
the creation of modular code. Because application components are independent objects,
it is possible to write code that can be reorganised and reused without influencing
other parts of the program. This allows sophisticated applications to be created with
fewer lines of code than would otherwise be required. Because each application
component is an object, it is possible to modify a single element without having to
update or redesign the entire application. This allows for a larger degree of customization Self-Instructional
in the development of applications that would otherwise be impossible. Material 9

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Object-Oriented Programming (OOP) is a programming paradigm based


on the concept of objects, which are data structures consisting of fields (attributes)
and procedures (functions or methods) as shown in Figure 1.3. Objects are
distinguished by the fact that their procedures provide access to and modify their
attributes.
Object-oriented programming involves building computer programs out of
objects that interact with one another. Object-oriented programming is highly diverse,
but the majority of languages are class-based, meaning that objects are instances of
classes.

Fig. 1.3 Data and Functions in Object-Oriented Programming

1.5.2 OOP Definition

Object-Oriented Programming (OOP) is defined as a method of modularizing


programmes by generating partitioned memory areas for both data and functions,
which can then be used as templates to create copies of such modules on demand.
Object-oriented programming entails generating classes, objects from those classes,
and applications, which are standalone executable programmes that utilise the objects.
Classes can be reused to generate new programmes after they have been built.
Object-oriented approach entails visualising programme components as objects that
belong to classes and are analogous to tangible items in the real world. Objects can
manipulate the other objects and have them interact with one another to reach a
desired result.

Self-Instructional
10 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

1.5.3 Benefits of Object-Oriented Programming NOTES

Given below are the benefits of the Object-Oriented programming:


1. Simplicity: Because software objects simulate real-world items, complexity is
decreased.
2. Modularity: Each object is a separate entity with internal workings independent
of the rest of the system.
3. Modifiability: It is simple to make minor changes to an OO program’s data
representation or methods. Changes within a class have no effect on the rest of
the program because the only public interface that the outside world has access
to, is through the use of methods.
4. Extensibility: Introducing a few new objects and updating certain old ones
can solve the problem of adding new features or adapting to changing operating
conditions.
5. Maintainability: Objects can be maintained separately, making it easier to
locate and fix problems.
6. Reusability: Objects can be reused across several programs.

1.5.4 Why is OOP Popular?

There are several significant reasons why object-oriented programming has become
the dominant programming paradigm over the past two decades. A few of them are
given below:
1. Object-oriented programming scales very well, from the simplest to the most
complex problems.
2. It provides a form of abstraction that resonates with the methods people use to
solve commonplace problems.
3. OOP provides a scalable approach to system development. It enables the
decomposition of complex systems into smaller, manageable objects, allowing
large-scale systems to be built with greater ease and maintainability.
4. OOP promotes flexibility to enable code to be written in a way that handles
various object types without explicitly knowing their specific implementation. Self-Instructional
Material 11

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 5. There are a growing number of libraries that facilitate the creation of applications
for numerous domains.
6. OOP aligns well with the design and development of graphical user interfaces
(GUIs).
7. Object-oriented programming is the most recent proposed solution to help and
solve the software crisis.

1.6 CHARACTERISTICS OF OOP

As its name suggests, Object-Oriented Programming or OOP refers to programming


languages that utilize objects. Object-oriented programming seeks to implement the
real-world entities such as inheritance, hiding, polymorphism, etc., in programming.
The primary goal of OOP is to bind together the data and the functions that operate on
them so that only the function can access the data. Given below are the characteristics
of OOP:
 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

1.6.1 Class

A class is an abstract data type that has been defined by the user. It is made up of data
members and member functions that may be accessed and used by instantiating the
class. It indicates the collection of attributes or methods shared by all objects of the
Self-Instructional same type. A class is similar to an object’s blueprint.
12 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

For Example: Consider the Class of Cars. There may be many cars with different NOTES
names and brands but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and
wheels, speed limits, and mileage are its properties.

1.6.2 Object

It is a fundamental unit of Object-Oriented Programming that represents real-world


entities. An Object is an instance of a Class. When a class is defined, no memory is
allocated; nevertheless, memory is allocated when the class is instantiated (i.e., an
object is formed). An object has a name, a state, and a behaviour. Each object contains
data as well as code for manipulating the data. Objects can interact without knowing
the specifics of each other’s data or code; all that is required is knowledge of the type
of message accepted and the type of response given by the objects.
For example, “Dog” is a real-life object, which has some characteristics like
colour, breed, and methods like Bark, Sleep, and Eats. Figure 1.4 gives another example
of Class having name ‘Bank Account’. Bank Account can have attribute/characteristics
like Account Number (A/C Number), name, age, gender. Each bank account can
have methods like deposit (), withdraw () to be performed. Object represent the
different bank account having their own values for attributes also known as data
members.

Fig. 1.4 Class and Object


Self-Instructional
Material 13

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 1.6.3 Data Abstraction

Data abstraction is one of the most significant aspects of object-oriented programming.


Data abstraction is the process of exposing only the essential information about a data
set to the outside world while hiding the background details or implementation. Consider
the following scenario: a man is driving an automobile. The man only knows that pressing
the accelerator will increase the speed of the car or applying the brakes will stop the
car, but he has no idea how pressing the accelerator increases the speed, nor does he
understand the inner mechanism of the car or how the accelerator, brakes, and other
controls are implemented in the car. This is the definition of abstraction. Another example
of abstraction is Bank_Account class representing a bank account. The class has
attributes account_number and balance, and methods deposit, withdraw, and
get_balance. The implementation details, such as how the balance is stored or how
deposits and withdrawals are processed, are hidden within the class.

1.6.4 Encapsulation

Encapsulation is the process of enclosing data in a single unit. It is the mechanism that
connects code and the data that it manipulates. Encapsulation means that a class’
variables or data remain hidden from other classes and can only be accessed through
member function of the class in which they are specified as shown in Figure 1.5.
Because the data in a class is hidden from other classes, it is sometimes referred to as
data hiding.

Self-Instructional
14 Material Fig. 1.5 Encapsulation in OOP

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

Consider a real-world example of encapsulation: in a firm, there are several NOTES


divisions such as the accounts section, the finance section, the sales section, and so on.
The finance sector manages all financial transactions and keeps track of all financial
data. Similarly, the sales section is in-charge of all sales-related activities and maintains
track of all sales. Now and again, an official from the finance department may require
complete sales data for a specific month for some reason. In this case, he is not
permitted to directly view the sales section’s data. He must first contact another officer
in the sales section and obtain specific info from him. Encapsulation is what it is. The
data of the sales section and the workers who can change it are bundled together
under the umbrella term “sales section” here.

1.6.5 Inheritance

Inheritance is a key component of OOP. Inheritance refers to a class’ ability to derive


features and traits from another class. Using inheritance concepts, properties and
functions need not be repeated because they can be inherited from another class
having those characteristics. Inheritance allows the user to reuse code as much as
possible, reducing repetition. Figure 1.6 shows the inheritance concepts and types of
inheritance. Class Vehicle represents base class whose attributes can be driven in
another class named Automobile (Motor driven) and Pulled vehicle. Each derive class
has their own properties as well as base class properties. More on inheritance will be
discussed in later chapters.

Fig. 1.6 Inheritance Mechanism in OOP

Self-Instructional
Material 15

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 1.6.6 Polymorphism

Having a variety of different forms is what is meant by the term polymorphism. The
capacity of a message to be presented in more than one form is an example of
polymorphism, which we can explain using more straightforward language. For instance,
one person can simultaneously exhibit a variety of qualities just like a man fulfils the
roles of father, spouse, and worker. Therefore, a person can behave differently
depending on the circumstances he is in. This phenomenon is known as polymorphism.
Figure 1.7 shows an example of polymorphism. Animal class can have different types
of animals that exhibit different properties but still belongs to same class, i.e., Animal
class.

Fig. 1.7 Polymorphism

1.6.7 Dynamic Binding

The code to be executed in response to a function call is determined at runtime in


dynamic binding. The code associated with a specific procedure call is not known until
the call is made at run time, which is referred to as dynamic binding. Dynamic binding
is also known as late binding or runtime polymorphism. Dynamic binding is achieved
through the use of virtual functions or methods. Dynamic binding allows for flexibility
and extensibility in OOP by enabling polymorphism. It enables different objects to
respond to the same message in different ways, facilitating code reuse and enhancing
the overall flexibility of the system.

Self-Instructional
16 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

1.6.8 Message Passing NOTES

It is a type of communication used in both object-oriented and parallel programming.


Objects communicate by delivering and receiving information from one another. A
message for an object is a request for the execution of a procedure, and it will thus
trigger a function in the receiving object that produces the desired effects. Message
passing entails specifying the object’s name, the function’s name, and the information
to be transmitted. Message passing allows objects to interact with each other in a
controlled and modular way, promoting code reusability and maintainability. It supports
the principles of encapsulation and information hiding, as objects determine how to
respond to messages internally without exposing their internal implementation details.

1.7 NEED OF OOP

OOP provides a clear structure to the programs. It makes the code easier to maintain,
modify and debug. OOP makes it possible to create full reusable applications with less
code and shorter development time. Following are the reasons that promote the use of
OOP:
 To make it easier to create projects and keep them running.
 To offer the ability to hide info, which is good for security.
 To solve problems that happen in the real world.
 Promotes code reusability.
 Avoids repeatedly re-writing the code.

In-Text Questions
1. Which of the following is NOT a fundamental principle of OOP?
a) Encapsulation b) Inheritance
c) Abstraction d) Compilation
2. What is the process of creating a new object from an existing object called?
a) Inheritance b) Encapsulation Self-Instructional
c) Polymorphism d) Copying Material 17

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 3. In C++, a class is a blueprint for creating:


a) Objects b) Functions
c) Arrays d) Structures
4. Which OOP concept allows a class to have multiple methods with the same
name but different parameters?
a) Encapsulation b) Inheritance
c) Polymorphism d) Abstraction
5. Which of the following is an advantage of using OOP?
a) Code reusability b) Tight coupling
c) Global variables d) Procedural programming
6. Which OOP feature allows a class to inherit properties and behaviour from
another class?
a) Polymorphism b) Abstraction
c) Encapsulation d) Inheritance

1.8 DIFFERENCE BETWEEN PROCEDURE-


ORIENTED PROGRAMMING AND OOP

Both Object-oriented programming and Procedure-oriented programming are used


to develop the applications. Both of them are high-level programming languages.
They both are significant and it is important to know the difference between them.
Table 1.1 gives the difference between Procedure-oriented and Object-oriented
Programming.

Self-Instructional
18 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

Table 1.1 Difference between POP and OOP NOTES

Difference Procedure-Oriented Object-Oriented Programming


Programming

Approach to Procedure-oriented OOP focuses on modelling real-


Problem programming focuses on world entities and their interactions
Solving breaking down a problem into a by creating objects
set of procedures or functions.
Program Procedure-oriented programs are Programs are structured around
Structure structured around procedures or classes and objects.
functions. The code is organized
into a series of procedures that
manipulate data.
Data and Data and behaviour are often OOP promotes the concept of
Behaviour separated. Data is stored in encapsulating data and behaviour
variables, and procedures within objects. Objects have their
manipulate that data. own internal state (data) and
methods (behaviour) that can
access and manipulate that data.
Code Code reusability in procedure- OOP facilitates code reusability
Reusability oriented programming is through the concept of inheritance
typically achieved by creating
reusable functions or procedures
Modularity Supports code modularity Classes encapsulate data and
through the use of procedures or behaviour, promoting code
functions. However, data and modularity and easier maintenance.
behaviour are often more
loosely coupled.
Data Less emphasis on data Promotes data abstraction by
Abstraction abstraction. Data is often providing mechanisms like
accessed directly, and the encapsulation, where the internal
internal details of data structures details of an object are hidden, and
are exposed. only essential information and
behaviour are exposed.
Security Less secure Highly secure

Self-Instructional
Material 19

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
1.9 SUMMARY

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating objects
that contain both data and functions. Object-oriented programming has several
advantages over procedural programming OOP is faster and easier when it comes to
creating projects also it provides a clear structure for the programs. OOP code is
easier to maintain, modify and debug and it makes it possible to create fully reusable
applications with less code and shorter development time.
In this lesson, many concepts of OOPs have been explored. OOP organises
code into classes and objects. It encapsulates data and functionality in object-oriented
programmes. C++, Java, Python, and C# employ OOP. OOP can help developers
produce cleaner, more organised, and efficient code.
1. OOP objects are instances of classes. Objects have attributes (state) and methods
(actions or operations).
2. Classes: A class is a template for a group of objects’ characteristics and
behaviour. It stores object data and functions. Classes generate objects.
3. Encapsulation: Bundling data and operations within a class hides internal
information and provides a public interface to interact with the object. It improves
code organisation, data protection, and control.
4. Inheritance: A derived class (subclass) can inherit properties and behaviour
from a base class (superclass). It encourages code reuse and class hierarchies.
5. Polymorphism: Polymorphism allows distinct classes to be handled as a
superclass. It allows one interface to represent several kinds and provides code
flexibility and expansion.
6. Abstraction: Abstraction simplifies and generalises complex systems. It hides
superfluous information and exposes only key functionality, helping developers
comprehend.
7. Modularity: OOP breaks complicated systems into manageable modules
(classes). Code organisation, reusability, and maintainability are improved by
Self-Instructional class specialisation.
20 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

8. OOP benefits include code reuse, modularity, extensibility, adaptability, and NOTES
code organisation. Better software design, developer cooperation, and scalable
codebases are possible with it.

1.10 GLOSSARY

 OOP: OOP stands for Object-Oriented Programming Language which utilises


objects.
 Object: It refers to an instance of a class that encapsulates data and behaviour.
 Class: It is a blueprint or template that defines the properties and methods that
an object of that class will have.
 Encapsulation: Encapsulation is the principle of bundling data and methods
together within a class and controlling access to them through public, private,
and protected access specifiers.
 Inheritance: It refers to the mechanism by which one class inherits properties
and behaviour from another class. It establishes a parent-child relationship between
classes, enabling code reuse and creating hierarchical structures.
 Polymorphism: It is the ability to use objects of different classes through a
common interface. It allows different objects to respond to the same message
or method in different ways.
 Abstraction: It refers to the process of creating simplified and generalized
representations of complex systems. It focuses on essential features while hiding
unnecessary details.

1.11 ANSWERS TO IN-TEXT QUESTIONS

1. d) Compilation
2. d) Copying
3. a) Objects Self-Instructional
Material 21

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 4. c) Polymorphism
5. a) Code reusability
6. d) Inheritance

1.12 SELF-ASSESSMENT QUESTIONS

Q1. What is object-oriented programming (OOP), and what are its key principles?
Q2. Explain the concept of encapsulation in OOP and provide an example.
Q3. What is the difference between a class and an object in OOP? Provide a brief
explanation.
Q4. Describe the concept of inheritance in OOP and provide an example to illustrate
it.
Q5. What is polymorphism in OOP? Explain the difference between compile-time
polymorphism and runtime polymorphism.
Q6. Describe the benefits of using OOP in software development.

1.13 REFERENCES

 Pohl, Ira. Object-oriented programming using C++. Benjamin-Cummings


Publishing Co., Inc., 1993.
 Stroustrup, Bjarne. “Multiple inheritance for C++.” Computing Systems 2.4
(1989): 367-395.
 Yang, Jing, et al. “Object model construction for inheritance in C++ and its
applications to program analysis.” Compiler Construction: 21st International
Conference, CC 2012, Held as Part of the European Joint Conferences on
Theory and Practice of Software, ETAPS 2012, Tallinn, Estonia, March
24–April 1, 2012. Proceedings 21. Springer Berlin Heidelberg, 2012.

Self-Instructional
22 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to OOP

 Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented NOTES


programming with C++. Vol. 4. Tata McGraw-Hill, 2008.
 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992.
 Oualline, Steve. Practical C++ programming. “ O’Reilly Media, Inc.”, 2003.
 Eckel, Bruce. C++ inside and out. McGraw-Hill, Inc., 1993.

1.14 SUGGESTED READING

 Barbara, Stanley B. Lippman Josée Lajoie, and E. Moo. “C++ Primer.” (2013).
 Meyers, Scott. Effective C++: 55 specific ways to improve your programs
and designs. Pearson Education, 2005.
 McLaughlin, Brett, Gary Pollice, and David West. Head First Object-Oriented
Analysis and Design: A Brain Friendly Guide to OOA&D. “ O’Reilly Media,
Inc.”, 2007.
 https://www.learncpp.com/
 http://www.cplusplus.com/doc/tutorial/oop/
 https://www.programiz.com/cpp-programming/object-oriented-programming

Self-Instructional
Material 23

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

LESSON 2 NOTES

INTRODUCTION AND BASIC CONCEPTS OF C++

Dr. Deepali Bajaj


Associate Professor
Shaheed Rajguru College of Applied Sciences for Women
University of Delhi
[email protected]
Seema
Assistant Professor
Shaheed Rajguru College of Applied Sciences for Women
University of Delhi
[email protected]
Structure
2.1 Learning Objectives
2.2 Introduction to C++
2.2.1 Features of C++
2.3 Basic Terminology of C++
2.3.1 Tokens
2.3.2 C++ Keywords
2.3.3 Identifiers
2.3.4 Variable
2.3.5 Constants
2.4 Data Types
2.4.1 Built-in Data Types in C++
2.4.2 Derived Data Types in C++
2.4.3 Abstract or User-Defined Data Types in C++
2.5 Structure of C++ Program
2.5.1 Comments
2.5.2 Naming Convention
2.5.3 Main Function
2.5.4 Input Output Statements
2.6 Summary
2.7 Glossary
2.8 Answers to In-Text Questions
2.9 Self-Assessment Questions
2.10 References Self-Instructional
2.11 Suggested Reading Material 25

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
2.1 LEARNING OBJECTIVES

 To familiarize students with the basic syntax and structure of C++ programs
 To explain the terminology related to C++ like variable, token, identifier and
constant
 To describe the usage of various data types and introduction to operators

2.2 INTRODUCTION TO C++

C++ is an Object-Oriented programming language. It was developed by Bjarne


Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. Initially the new
language was named as “C with Classes.” However, its name was changed to C++ in
1983. C++ is a powerful superset of the C programming language. The C++ was built
on the foundation of C. It includes all features, attributes, and benefits of C. Additional
features added to C were designed to support Object-Oriented programming. These
features comprise classes, inheritance, function overloading, and operator overloading.
C++ has many other new features as well, including an improved approach to input/
output (I/O) and a new way to write comments. C++ is used for developing high-
performance applications such as system software, game development, embedded
systems, editors, databases, personal file systems, networking utilities, and
communication programs. Since C++ shares C’s efficiency, many high-performance
system software are constructed using C++.
The name “C++” indicates the evolutionary nature of the language. The “++”
symbolizes the increment operator in C, suggesting that C++ builds upon and extends
the capabilities of C. C++ provides a higher level of abstraction and additional features,
making it more versatile and expressive than C.

2.2.1 Features of C++

C++ is a feature-rich programming language with a wide range of capabilities. Here


are some key features of C++:
Self-Instructional  Object-Oriented Programming (OOP): C++ supports OOP principles,
26 Material
allowing you to create classes and objects. It provides features like encapsulation,

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

inheritance, polymorphism, and facilitates code organization, reusability, and NOTES


modularity.
 Templates: C++ introduces templates, which enable generic programming.
Templates allow you to write functions and classes that can work with different
data types, providing flexibility and code reuse.
 Exception Handling: C++ provides a robust exception handling mechanism.
You can catch and handle exceptions to deal with runtime errors gracefully,
separating error handling from regular program flow.
 Memory Management: C++ offers manual memory management through
the use of pointers, allowing you to allocate and deallocate memory explicitly. It
gives you fine-grained control over resources. Additionally, C++ supports
automatic memory management using constructors, destructors, and smart
pointers, reducing the chances of memory leaks and dangling pointers.
 Multiple Inheritance: C++ allows a class to inherit properties and behaviours
from multiple base classes. Multiple inheritance can be useful in certain scenarios
where a class needs to combine features from different sources.
 Operator Overloading: C++ allows overloading of operators, which means
you can define custom behaviours for operators like +, -, *, /. This feature
enables more natural and intuitive syntax for custom types.
 Standard Library: C++ provides a rich standard library that offers a wide
range of functionalities, including input/output operations, string manipulation,
file handling, mathematical functions, and more. It saves developers time by
providing pre-implemented and efficient solutions for common programming
tasks.
 Compatibility with C: C++ is backward compatible with the C programming
language. You can seamlessly integrate C code into C++ programs, and C++
compilers can compile most C code.
 Performance: C++ is known for its performance and efficiency. It allows low-
level manipulation of memory and direct access to hardware resources, making
it suitable for systems where performance is critical. C++ is a versatile language
used in various domains, including game development, scientific computing,
finance, and embedded systems. It has a large and active community, with Self-Instructional
Material 27

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES extensive documentation, libraries, and frameworks available to support


development.
These are just some of the prominent features of C++. The language’s versatility
and extensive feature set makes it a popular choice for a wide range of applications,
from system-level programming to high-performance computing. Learning C++
provides a solid foundation for understanding programming concepts and enables you
to develop a wide range of applications.

2.3 BASIC TERMINOLOGY OF C++

Here, we will study the terms used in C++ such as tokens, keywords, identifiers,
variables and constants.

2.3.1 Tokens

As in the English language, in a paragraph, all the words, punctuation marks, and
blank spaces are called Tokens, all the C++ statements having Keywords, Identifiers,
Constants, Strings, Operators, and Special Symbols in a C++ program are also called
C++ Tokens. C++ Tokens are an essential part of a C++ compiler and are very useful
in C++ programming. A Token is an individual entity of a C++ program.
For example, some C++ Tokens used in a C++ program are as follows:
Reserve words: long, do, if, else etc.
Identifiers: Pay, salary etc.
Constant: 470.6,16,49 etc.
Strings: “Dinesh”, “2013-01” etc.

2.3.2 C++ Keywords

When a language is defined, one has to design a set of instructions to be used for
communicating with the computer to carry out specific operations. The words that are
Self-Instructional
used in programming language for special purpose are called keywords. These are
28 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

also known as reserved words of the language. They have a specific meaning for the NOTES
C++ compiler and should be used for giving specific instructions to the computer.
These words cannot be used for any other purpose, such as naming a variable. C++ is
a case-sensitive language and it requires that all keywords be in lowercase. C++
keywords are shown in Figure 2.1.

Fig. 2.1 C++ Keywords

2.3.3 Identifiers

Identifiers refer to the name of the variable, functions, array, class, etc., that are defined
by the programmer. Each language has its own rule for naming the identifiers. The
following rules are common for both C and C++:
1. Only alphabetic characters, digits and underscore are permitted.
2. The name can not start with a digit.
3. Upper case and lower case letters are distinct.
4. A declared keyword can not be used as a variable name.
5. An identifier must be unique in a program.
Self-Instructional
Material 29

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Examples of Identifiers

Po178_ddm //valid
_78hhvt4 //valid
902gt1 //invalid as it starts with a digit
Tyy;ui8 //invalid as it contains the ‘;’ character
for //invalid as it is a C++ keyword
Fg026 neo //invalid as it contains space

2.3.4 Variable

A variable is a named area in memory used to store values during program execution.
A variable has a symbolic name and can be given a variety of values. When a variable
is given a value, that value is actually placed in the memory space assigned to the
variable. It is required to declare variables before they can be used. The general form
of a declaration is:
type variable_list;
Here, type must be a valid data type plus any modifiers and variable_list may consist
of one or more identifier names separated by commas. Here are some declarations:
int i, j, l;
short int si;
unsigned int ui;
double balance, profit, loss;

2.3.5 Constants

Constants refer to fixed values that the program cannot alter. Constants can be of any
of the basic datatypes. The way each constant is represented depends upon its type.
Constants are also called literals.
We can use keyword ‘const’ prefix to declare constants with a specific type as follows:
const type variable Name = value;
For example,
Self-Instructional const int LENGTH = 10;
30 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

NOTES
2.4 DATA TYPES

A data type defines the size and type of values that a variable can store along with the
set of operations that can be performed on that variable. For example, a Boolean
variable can have Boolean data and an integer variable can hold integer data.
While coding, we require different variables to store different information. Variables
are storage locations reserved for storing values. Therefore, when you create the
variable, you reserve some space in memory. Figure 2.2 shows different data types
used in C++.
In C++, Data Types can be classified as follows:
1. Primitive/Built-in Data Types
2. Derived Data Types
3. Abstract/User-defined Data Types

Fig. 2.2 Data Types in C++

2.4.1 Built-in Data Types in C++

C++ provides built-in data types that correspond to integers, characters, floating-
point values, and Boolean values. There are seven basic data types in C++ as shown
below in Table 2.1.
Self-Instructional
Material 31

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Table 2.1 List of Built-in Data Types of C++

Data Type Meaning


Char Holds 8-bit ASCII characters
Int (Integer) Represents integer numbers having no fractional
part
Float (floating point) Represents number with real part
Double (Double floating point) Represents number with real part
Bool (Boolean) Can have only two possible values: true and false
Void Valueless

In C++, the char data type is used to represent individual characters. It is a


fundamental data type that can hold a single character from the ASCII character set.
Integer data type is used to represent number without decimal point whereas float and
double data types are used to represent numbers with decimal values. Boolean data type
is used to represent values which can be either true or false. In C++, the void data type
is used to indicate the absence of a type. It is often used as the return type of functions
that do not return a value or to declare functions that do not take any parameters. To
store information for different data types, such as integers, floats, strings and Boolean
values, memory is allocated based on the variable’s data type. Table 2.2 represents the
data type and memory required (in Bytes) for each built-in data type with range.
Table 2.2 Data Types and Required Memory Size (In Bytes)

Data Type Size (in Bytes) Range


int or signed int 4 Bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 Bytes 0 to 4,294,967,295
short int 2 Bytes -32,768 to 32,767
long int 8 Bytes -(2^63) to (2^63)-1
unsigned short int 2 Bytes 0 to 65,535
unsigned long int 8 Bytes 0 to 4,294,967,295
long long int 8 Bytes -(2^63) to (2^63)-1
unsigned long long 8 Bytes 0 to 18,446,744,073,709,551,615
int
signed char 1 Bytes -128 to 127
unsigned char 1 Bytes 0 to 255
wchar_t 2 or 4 Bytes 1 wide character
Self-Instructional float 4 Bytes 3.4*10^-38 to 3.4*10^38
32 Material
double 8 Bytes 1.7*10^-308 to 1.7 *10^ 308

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

The figure 2.3 and figure 2.4 shows the program and output of memory in bytes used NOTES
for built-in data types.

#include<bits/stdc++.h>
using namespace std;

int main() {
cout << “Size of following Datatypes in bytes:
\n”;
cout << “int : “ << sizeof(int) << endl;
cout << “unsigned int : “ << sizeof(unsigned int)
<< endl;
cout << “short int : “ << sizeof(short int) <<
endl;
cout << “long int : “ << sizeof(long int) << endl;
cout << “unsigned short int : “ << sizeof(unsigned
short int) << endl;
cout << “unsigned long int : “ << sizeof(unsigned
long int) << endl;
cout << “long long int : “ << sizeof(long long
int) << endl;
c ou t < < “ u n si gn e d l o n g l o n g i nt : “ < <
sizeof(unsigned long long int) << endl;
cout << “signed char : “ << sizeof(signed char) <<
endl;
cout << “unsigned char : “ << sizeof(unsigned
char) << endl;
cout << “wchar_t : “ << sizeof(wchar_t) << endl;
cout << “float : “ << sizeof(float) << endl;
cout << “double : “ << sizeof(double) << endl;
Fig. 2.3 Program to Find Size of Built-In Data Types

Output:
Size of following Datatypes in bytes:
int: 4
unsigned int: 4 Self-Instructional
short int: 2 Material 33

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES long int: 8


unsigned short int: 2
unsigned long int: 8
long long int: 8
unsigned long long int: 8
signed char: 1
unsigned char: 1
wchar_t : 4
float : 4
double : 8

Fig. 2.4 Memory Size in Bytes

2.4.2 Derived Data Types in C++

Derived Data Types are data types that are created by combining primitive or built-in
data types. There are four different types of derived data types. These are given
below:
1. Function: A function is a code segment or a block of code defined to accomplish
a specific purpose. A function is often designed to spare the user from repeatedly
writing the same lines of code for the same input. All the lines of code are
combined into a single function that may be invoked from anywhere. Every
C++ application includes a default function called main (). The function also has
a return type, which is used to specify the type of data the function would return
when its execution is complete.
2. Array: An array is a set of elements that are kept in memory in a continuous
manner and also have the same type of data present within the array. The purpose
of an array is to store a lot of data in a single variable name and sequential order.
3. Pointer: Pointers are symbolic representations of addresses. Pointers store the
addresses of the variables having the same data type as that of the pointer. The
size of the pointer is either 4 bytes or 8 bytes, no matter what the data type is.
4. Reference: When a variable is declared as a reference, it becomes an alternative
name for an existing variable. A variable can be declared as a reference by
putting '&' in the declaration.
Self-Instructional
34 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

2.4.3 Abstract or User-Defined Data Types in C++ NOTES

The Abstract data type, also known as user-defined data type, is a type of data defined
by the user.
Examples of these are as follows:
1. Class: A Class is a C++ building piece that leads to Object-Oriented
programming. It is a user-defined data type with its own set of data members
and member functions that can be accessed and used by establishing a class
instance. A class defines the blueprint for a data type.
2. Structure: A Structure data type is a user-defined data type that combines
objects of potentially different data types into a single type.
3. Enumeration: In C++, an enumeration (or enum) is a data type that the user
creates. It is primarily used to give integral constant names, making the program
easier to comprehend and maintain. In enumeration, if we do not provide the
integral values explicitly to the strings, then, in that case, the strings automatically
start assigning the integral values starting from value 0, the same as the case of
0-based indexing.
Example:
enum result {pass = 100, fail = 0};
Here, we have given the integer value 100 to be pass and 0 as fail; therefore, if
we write,
enum result res;
res = pass;
Then, the value of res would automatically be 100.
By default, the enumerators are assigned integer values starting with 0 for the
first enumerator, 1 for the second and so on. We can also write
enum color {red, blue=4,green=8};
enum color {red=5,blue,green};

Self-Instructional
Material 35

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
2.5 STRUCTURE OF C++ PROGRAM

Programs are a sequence of instructions or statements. These statements form the


structure of a C++ program. C++ program structure is divided into various sections,
namely, headers, class definition, member functions definitions and main function as
shown in Figure 2.5.

Fig. 2.5 Structure of a C++ Program

Note that C++ provides the flexibility of writing a program with or without a
class and its member functions definition. A simple C++ program (without a class)
includes comments, headers, namespace, main (), and input/output statements.
Now we will see first C++ program without classes.
My First C++ program
// A Simple C++ Program
#include<iostream.h>
using namespace std;
#include<conio.h>
int main()
{
cout<< “Hello SOL!!. It is a Simple C++ program without
using class”;
return 0;
}
Self-Instructional
36 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

2.5.1 Comments NOTES

Double slash (//) is used to represent comments. Comments are a vital element of a
program that are used to increase the readability of a program and to describe its
functioning. Comments are not executable statements and hence, do not increase the
size of a file. C++ supports two comment styles as given below:
i) Single line comment
ii) Multiline comment
Single line comments are used to define line-by-line descriptions. To understand
the concept of single line comment, consider this statement.
/ / An example to demonstrate single line comment It can also be written as
/ / An example to demonstrate
/ / single line comment
Multiline comments are used to define multiple lines descriptions and comments
are written within / * ….* /.
For example, consider this statement:
/* An example to demonstrate multiline comment.
Both of these lines are comments */
Generally, multiline comments are not used in C++ as they require more space on the
line. However, they are useful within the program statements where single-line comments
cannot be used.
Lines beginning with a hash sign (#) are directives that are read and interpreted
by what is known as the pre-processor. They are special lines interpreted before the
compilation of the program itself begins. In this case, the directive #include
<iostream.h>, instructs the pre-processor to include a section of standard C++
code, known as header iostream. The <iostream> header file provides the
necessary declarations and definitions for standard input/output streams to perform
operations, such as writing the output of program to the screen and taking input from
the keyboard.
Generally, a program includes various programming elements like built-in
functions, classes, keywords, constants, operators, etc., that are already defined in Self-Instructional
the standard C++ library. In order to use such pre-defined elements in a program, an Material 37

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES appropriate header must be included in the program. The standard headers contain
information like prototype, definition and return type of library functions, constants,
etc. As a result, programmers do not need to explicitly declare (or define) the predefined
programming elements.

2.5.2 Naming Convention

Namespace: Since its creation, C++ has gone through many changes by the C++
Standards Committee. One of the new features added to this language is namespace.
A namespace permits grouping of various entities like classes, objects, functions and
various C++ tokens, etc., under a single name. Different users can create separate
namespaces and thus can use similar names of the entities. This avoids compile-time
error that may exist due to identical-name conflicts.

2.5.3 Main Function

The function named main is a special function in all C++ programs; it is the function
called when the program is run. The execution of all C++ programs begins with the
main function, regardless of where the function is actually located within the code. The
compiler executes all the instructions written within the opening and closing curly braces’
{}’ that enclose the body of main ( ). Once all the instructions in main () are executed,
the control passes out of main ( ), terminating the entire program and returning a value
to the operating system.
The program ends with this statement:
return 0;
This causes zero to be returned to the calling process (which is usually the
operating system). Returning zero indicates that the program terminated normally.
Abnormal program termination should be signalled by returning a nonzero value.
The open brace ({) indicates the beginning of main’s function definition, and the
closing brace (}) indicates its end.

2.5.4 Input-Output Statements

Self-Instructional The objects cin and cout are pre-defined objects that serve as representations of the
38 Material
standard input and output streams, respectively. The standard output stream is a

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

representation of the display device, typically the screen, used for outputting data. NOTES
Conversely, the standard input stream is a representation of the input device, typically
the keyboard, used for accepting user input.
cout<< “Hello SOL!!. It is a Simple C++ program without
using class”;
causes the string in quotation marks to be displayed on the screen. The identifier
cout (pronounced as c out) denotes an object. It points to the standard output
device namely the console monitor. The operator << is called the insertion operator. It
directs the string on its right to the object on its left.
cin: It is the standard input stream that is associated with the standard input device
(keyboard) and is used to take the input from users.
cout: It is the standard output stream that is associated with the standard output
device (monitor) and is used to display the output to users.
The operator << is called the insertion operator and the operator >> is called
the extraction operator.
Figure 2.6 illustrates the usage of more C++ statements like cin and cout.

Fig. 2.6 Usage of more C++ Statements Like cin and cout
Self-Instructional
Material 39

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Cascading of I/O Operators

It is possible to use the insertion and extraction operators repeatedly in cin and cout
statements. Multiple use of these operators is called Cascading. For example, the
extraction operator can be cascaded as follows:
cout<<“ \n The value of a is “<<a ;
This statement first print “The value of a is” and then the value of variable a will be
printed. The insertion operator can be cascaded as follows:
cin>> a>>b;
The values are assigned from left to right.

In-Text Questions
Q 1. Which of the following is not the keyword in C++?
a) volatile b) for
c) enum d) cout
Q 2. ‘cin’ is an __
a) Class b) Object
c) Package d) Namespace
Q 3. A user defined header file is included by following statement in general.
a) #include “file.h” b) #include <file.h>
c) #include <file> d) #include file.h
Q 4. Which data type can be used to hold a wide character in C++?
a) unsigned char b) int
c) wchar_t d) none of the above
Q5. In CPP, cin and cout are the predefined stream __________ .
a) Operator b) Functions
c) Objects d) Data types

Self-Instructional
40 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

NOTES
2.6 SUMMARY

In C++, data types can be categorized into three main groups: built-in, derived, and
abstract. Built-in data types include fundamental types like integers (int), floating-point
numbers (float, double), characters (char), and boolean (bool), which store basic
values. Derived data types are constructed from the built-in types and include arrays,
pointers, and user-defined types like structures and classes. Abstract data types refer
to user-defined classes that encapsulate data and methods to represent complex
structures.
Tokens in C++ are called as building blocks of a program. All the sub-parts of
tokens are: keywords, identifiers, constants, strings, special symbols, and
operators equally important and play a vital role in framing the programs in C++.
A typical C++ program is structured with a main() function at its core, serving
as the entry point. It may include preprocessor directives, global variable declarations,
user-defined functions, and external library inclusion. The program’s logic is typically
organized into functions, and control flow is managed through conditional statements
(if, else) and loops (for, while). Objects and classes are used to create modular, reusable
code, and memory management is a crucial aspect, often managed through new and
delete operators or smart pointers. C++ also supports exception handling to deal with
errors gracefully. Proper understanding and utilization of these data types and program
structures are essential for developing efficient and robust C++ applications.

2.7 GLOSSARY

 Built-in Data Types: These are fundamental data types provided by the C++
language, including int (integers), float (floating-point numbers), double (double-
precision floating-point numbers), char (characters), and bool (boolean values).
 Derived Data Types: Data types constructed from built-in types or other
derived types. Examples include arrays (collections of elements of the same
data type) and pointers (variables that store memory addresses).
Self-Instructional
Material 41

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  Abstract Data Types (ADTs): User-defined data types created using classes
and encapsulating data and methods to represent complex structures. Examples
include classes that define objects with specific properties and behaviors.
 Main () Function: The core function in a C++ program, serving as the entry
point for program execution. It defines the starting point of program execution
and typically contains the program’s primary logic.
 Preprocessor Directives: Instructions to the C++ preprocessor, such as
#include for including external libraries and #define for defining constants and
macros.
 Global Variables: Variables declared outside of any function, making them
accessible throughout the entire program. They can be accessed and modified
from different functions.
 User-Defined Functions: Custom functions created by the programmer to
encapsulate specific blocks of code. They are invoked when needed to perform
a specific task, enhancing code modularity and reusability.
 Control Flow: The management of program execution based on conditions
and loops. Common control flow constructs in C++ include if-else statements
and for/while loops.
 Objects and Classes: Objects are instances of classes, which are user-defined
data types that bundle together data attributes (properties) and methods
(functions) to represent real-world entities or abstract concepts.
 Token: In programming, a token is the smallest individual unit of a program’s
source code. It can be a keyword, identifier, operator, or any other discrete
element with a specific meaning within the programming language.
 Keyword: Keywords are reserved words in a programming language that have
special meanings and purposes. They cannot be used as identifiers or variable
names. Examples in C++ include “int,” “if,” “else,” and “class.”
 Identifier: Identifiers are user-defined names used to represent variables,
functions, classes, and other program entities. They follow specific naming rules
and conventions.

Self-Instructional
42 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction and Basic Concepts of C++

NOTES
2.8 ANSWERS TO IN-TEXT QUESTIONS

1. (c) enum
2. (b) Object
3. (a) #include “file.h”
4. (c) wchar_t
5. (c) Objects

2.9 SELF-ASSESSMENT QUESTIONS

Q1. Define the structure of the C++ programs.


Q2. What do you mean by header files in C++? How do header files reduce the
compilation time and efforts of the programmer?
Q3. Define keywords. What are the keywords available in C++ language?
Q4. What is variable? How are they defined and initialized? Write important rules to
define a variable.

2.10 REFERENCES

 Pohl, Ira. Object-oriented programming using C++. Benjamin-Cummings


Publishing Co., Inc., 1993.
 Stroustrup, Bjarne. “Multiple inheritance for C++.” Computing Systems 2.4
(1989): 367-395.
 Yang, Jing, et al. “Object model construction for inheritance in C++ and its
applications to program analysis.” Compiler Construction: 21st International
Conference, CC 2012, Held as Part of the European Joint Conferences on
Theory and Practice of Software, ETAPS 2012, Tallinn, Estonia, March Self-Instructional
24–April 1, 2012. Proceedings 21. Springer Berlin Heidelberg, 2012. Material 43

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented


programming with C++. Vol. 4. Tata McGraw-Hill, 2008.

2.11 SUGGESTED READING

 Lafore, Robert. Object-oriented programming in C++. Pearson Education,


1997.

Self-Instructional
44 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
UNIT II: DATA TYPES AND EXPRESSIONS

LESSON 3 OPERATORS, EXPRESSIONS, TYPE


CASTING
Operators, Expressions, Type Casting

LESSON 3 NOTES

OPERATORS, EXPRESSIONS, TYPE CASTING

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
3.1 Learning Objectives
3.2 Arithmetic Operators
3.3 Assignment Operators
3.4 Relational Operators
3.5 Logical Operators
3.6 Bitwise Operators
3.7 Operators and their Precedence
3.8 Expressions
3.9 Typecasting in C++
3.9.1 Implicit Conversion
3.9.2 Explicit Conversion
3.10 Library Functions
3.11 Header Files and Library Files
3.11.1 Header Files
3.11.2 Library Files
3.12 #include Usage
3.12.1 System/Library Header Files
3.12.2 User-Defined Header Files
3.13 Solved Exercise
3.14 Summary
3.15 Glossary
3.16 Answers to In-Text Questions
3.17 Self-Assessment Questions
3.18 References
3.19 Suggested Readings Self-Instructional
Material 47

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
3.1 LEARNING OBJECTIVES

 To perform different operations such as arithmetic, assignment, relational, logical


and bitwise on variables and values
 To discuss the expressions, typecasting, library functions and header files

3.2 ARITHMETIC OPERATORS

Arithmetic operators are used to perform mathematical operations on data or values.


These are specified in Table 3.1
Table 3.1 Arithmetic Operators

Operator Name Description Syntax Example


Symbol

+ Addition Sum values on both p+q 8+7


sides of operator Output is 15
- Subtraction Subtracts right hand p–q 8-7
operand value from Output is 1
left hand operand
value
* Multiplication Multiplies values on p*q 8*7
both sides of Output is 56
operator
2.5 * 2
Binary Operators

Output is 5.0
/ Division Divides left hand p/q 8/2
operand value by Output is 4
right hand operand 6.2 / 3
value. Returns Output is 2.067
floating point 20 / 10
(decimal) Output is 2
% Modulus Divides left hand p%q 6%4
operand value by Output is 2
right hand operand
value and returns 10 % 30
remainder. It can Output is 10
Self-Instructional only be used with
48 Material integers.

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

NOTES
++ Increment Increases value by 1 ++p p=7
Pre-increment ++p will be 8
Unary Operator

p++
Post-increment
-- Decrement Decreases value by 1 --p p=7
Pre-increment --p will be 6

p--
Post-increment

Note: While using division operator, if both dividend and divisor are integers, result
obtained will be integer. However if either of them is float, result will also be float.
Example 3.1: Write a program to explain arithmetic operators in C++.
#include <iostream>
using namespace std;

int main() {
int variable1, variable2;
int sum, difference, product, quotient, remainder;

// Read two numbers from the user


cout << “Enter the first number: “;
cin >> variable1;

cout << “Enter the second number: “;


cin >> variable2;

// Perform arithmetic operations


sum = variable1 + variable2;
difference = variable1 - variable2;
product = variable1 * variable2;
quotient = variable1 / variable2;
remainder = variable1 % variable2;

// Display the results


Self-Instructional
cout <<endl<< “Sum: “ << sum ; Material 49

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout << endl<<“Difference: “ << difference ;


cout << endl<<“Product: “ << product ;
cout << endl<<“Quotient: “ << quotient ;
cout << endl<<“Remainder: “ << remainder ;

return 0;
}
Output
Enter the first number: 8
Enter the second number: 9
Sum: 17
Difference: -1
Product: 72
Quotient: 0
Remainder: 8

Explanation

In this program, the user is prompted to enter two numbers. The program then performs
various arithmetic operations on these numbers using the arithmetic operators. Finally,
the results are displayed.
Note: Operators which requires two operands to operate are binary operators, and
which require just one operator are termed as unary operators.
Example 3.2: Write a C++ program to illustrate post and pre increment operators.
#include <iostream>
using namespace std;

int main() {
int variable1= 5;
int variable2 = 10;

// Post-increment operator
Self-Instructional
50 Material cout << “Post-increment:” << endl;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

cout << “variable1: “ << variable1<< endl; NOTES


cout << “variable1++: “ << variable1++ << endl;
cout << “After post-increment, variable1: “ <<
variable1 << endl;

// Pre-increment operator
cout << “\nPre-increment:” << endl;
cout << “variable2: “ << variable2<< endl;
cout << “++variable2: “ << ++variable2 << endl;
cout << “After pre-increment, variable2: “ <<
variable2<< endl;

return 0;
}
Output
Post-increment:
variable1: 5
variable1++: 5
After post-increment, variable1: 6

Pre-increment:
variable2: 10
++variable2: 11
After pre-increment, variable2: 11

Explanation

In this program, we have two variables variable1 and variable2. First, we


demonstrate the post-increment operator variable1 ++, which evaluates the expression
and then increments the value of variable1 by 1. The result of the expression is
the original value of variable1. Then, we print the updated value of variable1.
Next, we demonstrate the pre-increment operator ++ variable2, which
Self-Instructional
first increments the value of variable2 by 1 and then evaluates the expression. The Material 51

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES result of the expression is the updated value of variable2. Finally, we print the
updated value of variable2.
Same logic is applied to post and pre decrement operator

3.3 ASSIGNMENT OPERATORS

Assignment operators are used to assign data values to variables. Assignment operators
are depicted in Table 3.2.
Table 3.2 Assignment Operators

Operator Description Syntax Example Output


Symbol r=10, p=6, q=2 (Unless
explicitly stated)
= Assigns value of right side r=p r =4 4
operand/expression to left side r is assigned value 4
operand.
r=p+q 8
p and q are added and
obtained value is
assigned to r
+= Adds right hand operand value r += p r= r + p 16
to left hand operand value r and p are added and
and assigns to left hand obtained value is
operand. assigned to r
-= Subtracts right hand operand r -= p r= r - p 4
value from left hand operand p is subtracted from r
value and assigns to left hand and obtained value is
operand. assigned to r
*= Multiplies right hand operand r *= p r= r * p 60
value to left hand operand p is multiplied r and
value and assigns to left hand obtained value is
operand. assigned to r
/= Divides left hand operand r /= p r=r/p 1
value by right hand operand
value and assigns to left hand
operand.
%= Divides left hand operand r %= p r%=p 4
value by right hand operand
Self-Instructional
value (returns remainder) and
52 Material assigns to left hand operand.

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

Example 3.3: Write a program to illustrate assignment operators in C++. NOTES


#include <iostream>
using namespace std;

int main() {
int variable1= 10;
int variable2= 5;

// Simple assignment
int result = variable1;
cout << “Simple assignment: “ << result << endl;

// Addition assignment
result += variable2;
cout << “Addition assignment: “ << result <<
endl;

// Subtraction assignment
result -= variable2;
cout << “Subtraction assignment: “ << result <<
endl;

// Multiplication assignment
result *= variable2;
cout << “Multiplication assignment: “ << result
<< endl;

// Division assignment
result /= variable2;
cout << “Division assignment: “ << result <<
endl;

// Modulus assignment
result %= variable2; Self-Instructional
Material 53

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout << “Modulus assignment: “ << result << endl;

return 0;
}
Simple assignment: 10
Addition assignment: 15
Subtraction assignment: 10
Multiplication assignment: 50
Division assignment: 10
Modulus assignment: 0
Explanation
In this program, we have two variables variable1 and variable2. We perform
various assignment operations using different assignment operators.
Simple assignment (=): Assigns the value of variable1 to the variable
result.
Addition assignment (+=): Adds the value of variable2 to result
and assigns the sum back to result.
Subtraction assignment (-=): Subtracts the value of variable2
from result and assigns the difference back to result.
Multiplication assignment (*=): Multiplies the value of result by
variable2 and assigns the product back to result.
Division assignment (/=): Divides the value of result by variable2
and assigns the quotient back to result.
Modulus assignment (%=): Computes the remainder of result divided by
variable2 and assigns the remainder back to result.

3.4 RELATIONAL OPERATORS

Self-Instructional Relational or comparison operators are used for comparison. They compare two
54 Material
values and return Boolean value ‘True’ or ‘False’. They are given in Table 3.3.

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

Table 3.3 Relational Operators NOTES


Operator Name Description Example Result
Symbol (p = 12, q =10)
> Greater than Compares two values and p>q True
returns ‘True’ if left
operand is greater than right
operand.
< Less than Compares two values and p<q False
returns ‘True’ if left
operand is less than right
operand.
== Equal to Compares two values and p == q False
returns ‘True’ if left
operand is equal to right
operand.
!= Not Equal to Compares two values and p != q True
returns ‘True’ if left
operand is not equal to right
operand.
<= Less than or Compares two values and p <= q False
equal to returns ‘True’ if left
operand is less than or
equal to right operand.
>= Greater than Compares two values and p >= q True
or equal to returns ‘True’ if left
operand is greater than or
equal to right operand.

Example 3.4: Write a program to illustrate relational operators.


#include <iostream>
using namespace std;

int main() {
int variable1= 5;
int variable2 = 10;

// Equal to operator
bool isEqual = (variable1 == variable2);
cout << “Equal to operator: “ << isEqual <<
Self-Instructional
endl; Material 55

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
// Not equal to operator
bool isNotEqual = (variable1 != variable2);
cout << “Not equal to operator: “ << isNotEqual
<< endl;

// Greater than operator


bool isGreaterThan = (variable1 > variable2);
cout << “Greater than operator: “ << isGreaterThan
<< endl;

// Less than operator


bool isLessThan = (variable1 < variable2);
cout << “Less than operator: “ << isLessThan <<
endl;

// Greater than or equal to operator


bool isGreaterThanOrEqual = (variable1 >=
variable2);
cout << “Greater than or equal to operator: “ <<
isGreaterThanOrEqual << endl;

// Less than or equal to operator


bool isLessThanOrEqual = (variable1 <= variable2);
cout << “Less than or equal to operator: “ <<
isLessThanOrEqual << endl;

return 0;
}
Output
Equal to operator: 0
Not equal to operator: 1
Greater than operator: 0
Less than operator: 1
Greater than or equal to operator: 0
Self-Instructional
56 Material Less than or equal to operator: 1

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

Explanation NOTES

In this program, we have two variables variable1 and variable2. We perform various
relational operations using different relational operators.
Equal to operator (==): Checks if variable1 is equal to variable2.
Not equal to operator (!=): Checks if variable1 is not equal to
variable2.
Greater than operator (>): Checks if variable1 is greater than variable2.
Less than operator (<): Checks if variable1 is less than variable2.
Greater than or equal to operator (>=): Checks if variable1
is greater than or equal to variable2.
Less than or equal to operator (<=): Checks if variable1
is less than or equal to variable2.
The result of each operation is stored in a boolean variable1 (true or
false) and then printed.

3.5 LOGICAL OPERATORS

These statements are used to check if expression statement is true or false. Table 3.4
shows various logical operators.
Table 3.4 Logical Operators

Operator Description Example Result


Symbol (p=2)
&& -and If both statements are True, Output (p < 5) && (p < 10) True
will be True
|| - or If anyone statement is True, (p < 5) || (p < 2) True
Output will be True.
! - not Returns opposite of result. ! ((p < 5) || (p < 2)) False

Example 3.5: Write a program to illustrate logical operators.


#include <iostream>
using namespace std;
Self-Instructional
Material 57

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES int main() {


bool variable1 = true;
bool variable2 = false;

// Logical AND operator


bool resultAND = variable1 && variable2;
cout << “Logical AND operator: “ << resultAND <<
endl;

// Logical OR operator
bool resultOR = variable1 || variable2;
cout << “Logical OR operator: “ << resultOR <<
endl;

// Logical NOT operator


bool resultNOT = ! variable1;
cout << “Logical NOT operator: “ << resultNOT <<
endl;

return 0;
}
Logical AND operator: 0
Logical OR operator: 1
Logical NOT operator: 0

Explanation

In this program, we have two boolean variables variable1 and variable2.


We perform various logical operations using different logical operators.
Logical AND operator (&&): Checks if both variable1 and
variable2 are true. It returns true if both operands are true, otherwise, it returns
false.
Logical OR operator (||): Checks if either variable1 or variable2
is true. It returns true if at least one of the operands is true, otherwise, it returns false.
Self-Instructional Logical NOT operator (!): Negates the value of variable1. If
58 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

variable1 is true, the NOT operator returns false, and if variable1 is false, NOTES
it returns true.
The logical operators evaluate the logical conditions and return a boolean result
based on the evaluation

3.6 BITWISE OPERATORS

Bitwise operators are used to manipulate individual bits of integer types. They perform
operations at the bit level, allowing you to perform tasks such as bit manipulation,
bitwise logical operations, and shifting.
Table 3.5 Bitwise Operators

Operator Description
Performs a bitwise AND int a = 5; // Binary:
operation between the 0101
corresponding bits of two int b = 3; // Binary:
& Bitwise AND 0011
operands.
int result = a & b; //
Binary: 0001
Performs a bitwise OR operation int a = 5; // Binary:
between the corresponding bits 0101
of two operands. int b = 3; // Binary:
| Bitwise OR 0011
int result = a | b; //
Binary: 0111
Performs a bitwise exclusive OR int a = 5; // Binary:
(XOR) operation between the 0101
corresponding bits of two int b = 3; // Binary:
^ Bitwise XOR 0011
operands.
int result = a ^ b; //
Binary: 0110
Flips the bits of the operand, i.e., Flips the bits of the operand, i.e.,
~ Bitwise Not
performs a bitwise negation. performs a bitwise negation.
Shifts the bits of the left operand int a = 5; //
to the left by the number of Binary: 0101
Binary Shift
<< positions specified by the right int result = a << 2;
Left // Binary: 010100
operand.
(Decimal: 20)
Shifts the bits of the left operand Shifts the bits of the left operand
Binary Shift to the right by the number of to the right by the number of
>>
Right positions specified by the right positions specified by the right
operand. operand. Self-Instructional
Material 59

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Example 3.6: Write a C++ program to illustrate bitwise operators.


#include <iostream>
using namespace std;

int main() {
int a = 10; // Binary: 1010
int b = 6; // Binary: 0110

// Bitwise AND
int resultAnd = a & b;
cout << “Bitwise AND: “ << resultAnd << endl; // Output: 2 (Binary: 0010)

// Bitwise OR
int resultOr = a | b;
cout << “Bitwise OR: “ << resultOr << endl; // Output: 14 (Binary: 1110)

// Bitwise XOR
int resultXor = a ^ b;
cout << “Bitwise XOR: “ << resultXor << endl; // Output: 12 (Binary:
1100)
// Bitwise NOT
int resultNot = ~a;
cout << “Bitwise NOT: “ << resultNot << endl; /
/ Output: -11 (Binary: 111111111111111111111111111
10101)

// Left Shift
int resultLeftShift = a << 2;

Self-Instructional
60 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

cout << “Left Shift: “ << resultLeftShift << NOTES


endl; // Output: 40 (Binary: 101000)

// Right Shift
int resultRightShift = a >> 2;
cout << “Right Shift: “ << resultRightShift <<
endl; // Output: 2 (Binary: 10)

return 0;
}
Operators
Bitwise AND: 2
Bitwise OR: 14
Bitwise XOR: 12
Bitwise NOT: -11
Left Shift: 40
Right Shift: 2
This program demonstrates the usage of bitwise AND, OR, XOR, NOT, left
shift, and right shift operators. It performs the operations on two integer variables a
and b and outputs the results.

3.7 OPERATORS AND THEIR PRECEDENCE

In C++, operators have different precedence levels, which determine the order in
which they are evaluated when multiple operators are present in an expression. If
two operators have the same precedence, their evaluation order depends on the
associativity of the operators. Table 3.6 depicts operators in highest to lowest
precedence.

Self-Instructional
Material 61

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Table 3.6 Operators in Highest to Lowest Precedence

Precedence Operator Description Associativity


1 ++ postfix increment Left to Right
-- postfix decrement
2 ++ prefix increment Right to Left
-- prefix decrement
! Logical Not
~ Bitwise Not
3 a * b Multiplication Left to Right
a / b Division
a%b Modulus
4 a + b Addition Left to Right
a-b Subtraction
5 << Bitwise left shift Left to Right
>> Bitwise right shift
6 < Less than Left to Right
<= Less than or equal to
> Greater than
>= Greater than or equal to
7 == Equal to Left to Right
!= Not equal to
8 & Bitwise AND Left to Right
9 ^ Bitwise XOR Left to Right
10 | Bitwise OR Left to Right
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 = Assignment Right to Left
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/+ Division Assignment
%= Modulus Assignment

Associativity specifies direction in which an expression will be evaluated.


In Table 3.6, Precedence 1 is highest and precedence 13 is lowest.
Example 3.7: Program to illustrate operator precedence.
#include <iostream>
using namespace std;

Self-Instructional int main() {


62 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

int result1 = 2 + 3 * 4; // Multiplication NOTES


has higher precedence than addition
int result2 = (2 + 3) * 4; // Parentheses
override the default precedence

int result3 = 10 / 2 - 3; // Division and


subtraction have the same precedence, evaluated from
left to right
int result4 = 10 / (2 - 3); // Parentheses
override the default precedence

int result5 = 2 * 3 + 4 * 5; // Multiplication


has higher precedence than addition
int result6 = (2 * 3) + (4 * 5); // Parentheses
override the default precedence

cout << “Result 1: “ << result1 << endl; //


Output: 14
cout << “Result 2: “ << result2 << endl; //
Output: 20
cout << “Result 3: “ << result3 << endl; //
Output: 2
cout << “Result 4: “ << result4 << endl; //
Output: -10
cout << “Result 5: “ << result5 << endl; //
Output: 26
cout << “Result 6: “ << result6 << endl; //
Output: 26

return 0;
}
Output
Result 1: 14
Result 2: 20
Result 3: 2
Self-Instructional
Result 4: -10 Material 63

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Result 5: 26
Result 6: 26
Expressions involving addition, subtraction, multiplication, and division operators
are evaluated. The results are stored in different variables (result1 to result6) to
demonstrate the effect of operator precedence and the use of parentheses to override
it.
Example 3.8: Write a program to show operator associativity.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 5, c = 2;
int result1 = a - b - c; // Left associativity:
Evaluates from left to right
int result2 = a / b / c; // Left associativity:
Evaluates from left to right
int result3 = a % b % c; // Left associativity:
Evaluates from left to right

cout << “Result 1: “ << result1 << endl;


// Output: 3
cout << “Result 2: “ << result2 << endl;
// Output: 1
cout << “Result 3: “ << result3 << endl;
// Output: 0

int result4 = a = b = c; // Right associativity:


Evaluates from right to left

cout << “Result 4: “ << result4 << endl;


// Output: 2
cout << “a: “ << a << endl; // Output: 2
cout << “b: “ << b << endl; // Output: 2
cout << “c: “ << c << endl; // Output: 2

return 0;
Self-Instructional
64 Material }

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

Output NOTES
Result 1: 3
Result 2: 1
Result 3: 0
Result 4: 2
a: 2
b: 2
c: 2

Explanation

The result1, result2, and result3 variables showcase left associativity.


The subtraction, division, and modulo operations are evaluated from left to right.
The result4 variable demonstrates right associativity by assigning the value
of c to b, and then assigning the resulting value of b to a.

3.8 EXPRESSIONS

An expression is a combination of literals, variables, operators, and function calls that


evaluates to a value. Expressions can be simple, consisting of a single variable or
literal, or they can be complex, involving multiple operations and sub-expressions.
Examples of Expressions
Arithmetic Expressions: int result = 2 + 3 * 4 - 5; //
Arithmetic expression involving
addition, multiplication, and
subtraction
double average = (num1 + num2) / 2.0;
// Arithmetic expression involving
variables and division
Relational Expressions: bool isEqual = (num1 == num2); //
Relational expression comparing
equality
bool isGreater = (num1 > num2); //
Relational expression comparing Self-Instructional
greater than Material 65
Logical Expressions: bool condition = (num1 > 0) && (num2

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Logical Expressions: bool condition = (num1 > 0) && (num2


< 10); // Logical expression using
the logical AND operator
bool isValid = (num1!= 0) || (num2 !=
0); // Logical expression using
the logical OR operator
Assignment Expressions: int x = 10; // Assignment
expression
y += 5; // Compound
assignment expression (equivalent to
y = y + 5)

Expressions can be composed in a variety of ways by combining operators and


operands to perform calculations, comparisons, assignments, and more.

3.9 TYPECASTING IN C++

Typecasting refers to the process of converting one data type into another. It allows
you to explicitly specify the desired type conversion and can be used to convert between
built-in types, user-defined types, or even between related types. We will discuss two
types of typecasting.

3.9.1 Implicit Conversion

Implicit conversions are performed automatically by the compiler when the conversion
is safe and does not result in a loss of data. For example, converting an int to a float or
assigning a smaller integer type to a larger integer type.
Example 3.9: Write a program to show implicit conversion.
#include <iostream>
using namespace std;

int main() {
int num1 = 10;
double num2 = num1; // Implicit conversion
from int to double
Self-Instructional
66 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

cout << “num1: “ << num1 << endl; // Output: 10 NOTES


cout << “num2: “ << num2 << endl; // Output: 10.0

char ch = ‘A’;
int ascii = ch; // Implicit conversion from
char to int

cout << “ch: “ << ch << endl; // Output: A


cout << “ascii: “ << ascii << endl; // Output: 65

int a = 5;
int b = 2;
double result = a / b; // Implicit conversion
during integer division

cout << “result: “ << result << endl;// Output: 2.0

return 0;
}
Output
num1: 10
num2: 10
ch: A
ascii: 65
result: 2

Explanation

In this program, implicit typecasting is demonstrated.


An int value is implicitly converted to a double when assigned to num2.
A char value ‘A’ is implicitly converted to its corresponding ASCII value
when assigned to ascii.
During integer division, the int values of a and b are implicitly converted to Self-Instructional
double before performing the division, resulting in a double value assigned to result. Material 67

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 3.9.2 Explicit Conversion

The use of explicit conversion changes data values from one type to another.

3.9.2.1 C-style Type Casting

C-style casting involves using casting operators such as (type) or type(value) to perform
explicit type conversions. It can be used to perform various conversions, but it can
also be potentially unsafe if used incorrectly.
Example 3.10: Write a program that demonstrates C-style type casting.
#include <iostream>
using namespace std;

int main() {
int num1 = 10;
double num2 = (double)num1; // C-style casting
from int to double

cout << “num1: “ << num1 << endl; // Output: 10


cout << “num2: “ << num2 << endl; // Output: 10.0

int a = 5;
int b = 2;
double result = (double)a / b; // C-style casting
during integer division

cout << “result: “ << result << endl; // Output: 2.5

char ch = ‘A’;
int ascii = (int)ch; // C-style casting
from char to int
cout << “ch: “ << ch << endl; // Output: A
cout << “ascii: “ << ascii << endl; // Output: 65

return 0;
Self-Instructional }
68 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

Output NOTES
num1: 10
num2: 10
result: 2.5
ch: A
ascii: 65

Explanation

An int value num1 is explicitly cast to a double using (double)num1.


C-style casting is used during integer division, casting a to double before
performing the division.
A char value ‘A’ is explicitly cast to its corresponding ASCII value using
(int)ch.

3.9.2.2 Static Cast

static_cast is a safer alternative to C-style casting. It performs compile-time


type checking to ensure the validity of the conversion. It can be used for a wide range
of conversions, such as numeric conversions, pointer conversions, and more.
Example 3.11: Program to show static cast.
#include <iostream>
using namespace std;

int main() {
int num1 = 10;
double num2 = static_cast<double>(num1); // Static
cast from int to double

cout << “num1: “ << num1 << endl; // Output: 10


cout << “num2: “ << num2 << endl; // Output: 10.0

int a = 5;
Self-Instructional
int b = 2; Material 69

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES double result = static_cast<double>(a) / b; //


Static cast during integer division

cout << “result: “ << result << endl; // Output: 2.5

char ch = ‘A’;
int ascii = static_cast<int>(ch); // Static cast
from char to int

cout << “ch: “ << ch << endl; // Output: A


cout << “ascii: “ << ascii << endl; // Output: 65

return 0;
}
Output
num1: 10
num2: 10
result: 2.5
ch: A
ascii: 65

Explanation

An int value num1 is explicitly cast to a double using


static_cast<double>(num1).
static_cast is used during integer division to cast a to double before
performing the division.
A char value ‘A’ is explicitly cast to its corresponding ASCII value using
static_cast<int>(ch).

Self-Instructional
70 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

NOTES
3.10 LIBRARY FUNCTIONS

A rich set of library functions is available in C++ that cover a wide range of functionality.
Here are some commonly used libraries in C++ and their functions:
1. <iostream>: Input/output operations.
std::cin: Reads input from the user.
std::cout: Writes output to the console.
std::endl: Inserts a newline character and flushes the output stream.
std::getline: Reads a line of input from the user.
2. <cmath>: Mathematical functions.
std::sqrt: Calculates the square root of a number.
std::pow: Raises a number to a power.
std::sin, std::cos, std::tan: Trigonometric functions.
std::abs: Returns the absolute value of a number.
3. <string>: String manipulation operations.
std::string: Represents a sequence of characters.
std::getline: Reads a line of input from a stream into a string.
std::substr: Extracts a substring from a string.
std::find: Searches for a character or substring within a string.
4. <fstream>: File input/output operations.
std::ifstream: Reads input from a file.
std::ofstream: Writes output to a file.
std::getline: Reads a line from a file into a string.
std::open: Opens a file for reading or writing.
These are just a few examples of the libraries and functions available in C++.
The C++ Standard Library provides many more functions and containers to handle
various programming tasks efficiently.
Self-Instructional
Material 71

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
3.11 HEADER FILES AND LIBRARY FILES

In C++ programming, header files and library files play important roles in organizing
and reusing code. Here is a brief explanation of each:

3.11.1 Header Files

 A header file is a file with the extension ‘.h‘


 It contains function declarations, class definitions, constants, and other
declarations.
 Header files are typically used to share declarations among multiple source
files.
 The content of a header file is usually included (using the #include directive) in
the source files that need the declarations from the header.
 Examples of commonly used header files in C++ include <iostream> and
<string>. These header files provide declarations for standard library
functions and classes.

3.11.2 Library Files

 Library files (also called binary or object files) are compiled code files that
contain precompiled functions and classes.
 Library files have file extensions like ‘.lib‘ (Windows) or ‘.a‘ (Unix/Linux) for
static libraries, and ‘.dll‘ (Windows) or ‘.so‘ (Unix/Linux) for dynamic/shared
libraries.
 Library files provide precompiled code that can be linked with your program at
compile-time or runtime.
 They can include functions, classes, data structures, and other code that can be
used by your program without needing to reimplement them.
 Library files can be either system libraries (provided by the operating system)
Self-Instructional or third-party libraries (developed by external developers).
72 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

 To use a library in your C++ program, you typically need to include the NOTES
appropriate header file(s) and link against the library file(s).
It is worth noting that header files and library files are closely related. Header
files provide declarations for the functions and classes in library files, while library files
contain the compiled implementations of those functions and classes. When writing
C++ programs, it is common to include necessary header files and link against required
library files to access their functionalities and reuse existing code.

3.12 #include USAGE

The #include directive is used to include header files into your program. There
are two common ways to use #include in C++, which are discussed here.

3.12.1 System/Library Header Files

#include <header_file>
In this form, the angle brackets ‘< >’ are used to enclose the header file name.
This syntax is typically used for including standard library header files or system-level
header files. The compiler will search for these header files in the standard system
directories.
Example:
#include <iostream>
#include <vector>

3.12.2 User-Defined Header Files

#include “header_file”
In this form, double quotation marks ‘“ ”’ are used to enclose the header file
name. This syntax is typically used for including user-defined header files that are
present in the current directory or in specified paths.
Example:
#include “my_header.h” Self-Instructional
Material 73

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Both forms of #include directives allow you to bring in the declarations
and definitions from the included header files into your C++ program. This enables
you to use the functions, classes, and other entities defined in those header files in your
code.
It is worth noting that header files usually contain declarations, not definitions. Definitions
for the declarations in the header files are typically found in corresponding
implementation files (e.g., ‘.cpp‘ files) or library files.

3.13 SOLVED EXERCISE

1. Write a program to demonstrate calculator.


i. Create a simple calculator program that takes two numbers and performs
arithmetic operations on them based on user input.
ii. Prompt the user to enter two numbers.
iii. Display a menu of operations for the user to choose from: addition,
subtraction, multiplication, and division.
iv. Read the user’s choice of operation.
v. Perform the selected operation on the two numbers and display the result.
#include <iostream>
using namespace std;

int main() {
// Prompt for two numbers
cout << “Enter two numbers: “;
double num1, num2;
cin >> num1 >> num2;

// Display menu
cout << “Select an operation:\n”;
cout << “1. Addition\n”;
Self-Instructional
74 Material
cout << “2. Subtraction\n”;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

cout << “3. Multiplication\n”; NOTES


cout << “4. Division\n”;

// Read user’s choice


int choice;
cout << “Enter your choice (1-4): “;
cin >> choice;

// Perform the selected operation and display the


result
double result;
switch (choice) {
case 1:
result = num1 + num2;
cout << “Result: “ << result << endl;
break;
case 2:
result = num1 - num2;
cout << “Result: “ << result << endl;
break;
case 3:
result = num1 * num2;
cout << “Result: “ << result << endl;
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
cout << “Result: “ << result << endl;
} else {
cout << “Error: Division by zero is
not allowed.\n”;
}
break;
default:
cout << “Invalid choice!\n”; Self-Instructional
Material 75

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES break;
}

return 0;
}
Output
Enter two numbers: 5
9
Select an operation:
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice (1-4): 3
Result: 45

Explanation

Program prompts you to enter two numbers and select an operation to perform. After
you make a choice, the program will calculate the result and display it.
2. Write a program that converts temperature between Celsius and Fahrenheit
scales.
#include <iostream>
using namespace std;

int main() {
// Prompt for temperature
cout << “Enter a temperature value: “;
double temperature;
cin >> temperature;

Self-Instructional
// Display menu
76 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

cout << “Select conversion direction:\n”; NOTES


cout << “1. Celsius to Fahrenheit\n”;
cout << “2. Fahrenheit to Celsius\n”;

// Read user’s choice


int choice;
cout << “Enter your choice (1 or 2): “;
cin >> choice;

// Perform the selected conversion and display


the result
double convertedTemperature;
switch (choice) {
case 1:
convertedTemperature = (temperature *
9 / 5) + 32;
cout << “Converted temperature: “ <<
convertedTemperature << “ degrees Fahrenheit\n”;
break;
case 2:
convertedTemperature = (temperature - 32)
* 5 / 9;
cout << “Converted temperature: “ <<
convertedTemperature << “ degrees Celsius\n”;
break;
default:
cout << “Invalid choice!\n”;
break;
}

return 0;
}
Output
Enter a temperature value: 45
Self-Instructional
Select conversion direction: Material 77

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 1. Celsius to Fahrenheit


2. Fahrenheit to Celsius
Enter your choice (1 or 2): 1
Converted temperature: 113 degrees Fahrenheit

Explanation

Program prompts to enter a temperature and select the conversion direction. After
you make a choice, the program will perform the conversion and display the converted
temperature.

In-Text Questions
1. What is the result of the expression: 10 % 3?
a) 1 b) 3
c) 0 d) 10
2. What does the following expression evaluate to: (5 > 3) && (4 < 2)?
a) true b) false
c) 1 d) 0
3. What is the associativity of the assignment operator (=) in C++?
a) Right to left b) Left to right
c) Top to bottom d) Bottom to top
4. Which operator is used to perform explicit typecasting in C++?
a) () b) <>
c) ** d) ><
5. Which operator is used to determine the size of an object or data type in
C++?
a) sizeof b) size
c) sizeofof d) memoryof

Self-Instructional
78 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

NOTES
3.14 SUMMARY

Operators in C++ are symbols or keywords used to perform operations on data.


They include arithmetic operators for math, relational operators for comparisons, logical
operators for boolean logic, assignment operators for variable assignment, and bitwise
operators for binary-level manipulation. The conditional (ternary) operator allows for
conditional value assignment. Expressions are combinations of operators, variables,
and literals that evaluate to a value. They can be arithmetic expressions for numerical
calculations, boolean expressions for true or false results, and conditional expressions
that return values based on conditions.
Type casting involves converting data from one data type to another. In C++,
there are two main types: implicit and explicit. Implicit type conversion is done
automatically by the compiler, while explicit type conversion is performed by the
programmer using casting operators like static_cast and dynamic_cast. Type casting
can be narrowing (may result in data loss) or widening (generally safe), and C-style
type casting is discouraged in modern C++ in favour of more robust alternatives.

3.15 GLOSSARY

 Arithmetic Operators: Symbols used for mathematical calculations, such as


addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
 Relational Operators: Operators that compare values, including equality (==),
inequality (!=), less than (<), less than or equal to (<=), greater than (>), and
greater than or equal to (>=).
 Logical Operators: Operators used for boolean logic, such as logical AND
(&&), logical OR (||), and logical NOT (!).
 Assignment Operator: The equal sign (=) is used to assign a value to a variable.
 Increment and Decrement Operators: The increment (++) and decrement
(—) operators are used to increase or decrease the value of a variable by 1.
Self-Instructional
Material 79

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  Bitwise Operators: Operators that perform operations at the binary level,
including bitwise AND (&), bitwise OR (|), bitwise XOR (^), and bit shifting
(<< and >>).
 Conditional (Ternary) Operator: A shorthand operator represented as ? : that
allows you to assign a value based on a condition.
 Expression: A combination of operators, variables, and literals that evaluates
to a value. For example, x + y is an expression.
 Type Casting (Type Conversion): The process of converting a value from
one data type to another. In C++, it can be explicit or implicit.

3.16 ANSWERS TO IN-TEXT QUESTIONS

1. a) 1
2. b) false
3. b) Left to right
4. a) ()
5. a) sizeof

3.17 SELF-ASSESSMENT QUESTIONS

Q1. Describe the purpose and use of conditional statements (if, else) in C++.
Provide examples.
Q2. What are loops in C++? Explain the difference between for, while, and
do-while loops with examples.
Q3. Define and explain the concept of functions in C++. Provide an example of a
user-defined function.
Q4. How can you explicitly convert data from one data type to another in C++?
Self-Instructional
Give examples of type casting.
80 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Operators, Expressions, Type Casting

NOTES
3.18 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


 Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented
programming with C++. Vol. 4. Tata McGraw-Hill, 2008

3.19 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
Material 81

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
UNIT III: CONTROL CONSTRUCTS IN C++

LESSON 4 DECISION CONTROL STATEMENTS IN


C++

LESSON 5 LOOPS IN C++


Decision Control Statements in C++

LESSON 4 NOTES

DECISION CONTROL STATEMENTS IN C++

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
4.1 Learning Objectives
4.2 Introduction
4.3 if Statement
4.4 if-else Statement
4.5 Nested if Statement
4.6 if-else-if Ladder
4.7 switch Statement
4.8 Conditional Operator
4.9 Summary
4.10 Glossary
4.11 Answers to In-Text Questions
4.12 Self-Assessment Questions
4.13 References
4.14 Suggested Readings

4.1 LEARNING OBJECTIVES

 To understand the if statement


 To discuss the use of if-else statement, nested if statement and if-
else-if ladder
 To explain switch statement
Self-Instructional
 To describe the overview of conditional operator Material 85

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
4.2 INTRODUCTION

In daily life, we take many decisions, like …. Shall I go for shopping? If I go for
shopping, shall I purchase jeans or not? In C++ programming also we need to make
decisions to handle the flow of program. For decision making purpose, decision
statements are used in C++. They evaluate condition(s) and based on the outcome,
the decision regarding whether the statement(s) is executed or not is taken and the
flow of program is decided.
Decision making statements govern the flow of program execution in C++. They are
also known as conditional statements. Decision making statements used in C++ are
as follows:
 if Statement
 if-else Statement
 Nested if Statement
 if-else-if Ladder
 switch Statement
 Conditional Operator
They are discussed one by one below.

4.3 if STATEMENT

if statement in C++ is the basic decision making statement. It accepts Boolean


values, checks if the condition is true or false. If the condition is true then statement or
block of statements underneath are executed. If the condition is false, then statement
or block of statements underneath are not executed. Structure of if statement is depicted
below:
if (condition)
{
Self-Instructional
86 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

// Statement(s) are executed if condition evaluates NOTES


to true
}
if condition is Boolean expression, and evaluates to true or false. Depending
on the result of Boolean expression, statements are executed. If curly braces are not
specified in code, then if condition only considers first statement after if condition for
evaluation. {} specifies block of statements.

Fig. 4.1 Flow Chart of if statement

Example 4.1: Write a program to print if number is even.


#include <iostream>
using namespace std;
int main()
{
int variable;
cout << “Enter variable to check: “ ;
cin>> variable; Self-Instructional
Material 87

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES if (variable % 2 == 0)
{
cout<< variable <<“ is even number”;
}
cout<< “ \n I am not part of if statement block”;
//this is always executed
return 0;
}
Output
Enter variable to check: 68
68 is even number
I am not included in if statement

4.4 if-else STATEMENT

if statements execute block only if condition evaluates to true. There are situations
when statements need to be executed for both true and false, i.e., we need to execute
certain statements when condition evaluates to true and some other statements when
condition evaluates to false. In that case, if-else statement is used. Structure of
if-else statement is depicted below.
if (expression statement)
{
// Statement(s) are executed if expression statement
evaluates to true
}
else
{
// Statement(s) are executed if expression statement
evaluates to false
}

Self-Instructional
88 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

NOTES

Fig. 4.2 Flow chart of if-else statement

Example 4.2: Write a program to print if entered number is even or odd.


#include <iostream>
using namespace std;
int main()
{
int variable;
cout << “Enter Number: “ ;
cin>> variable;
Self-Instructional
if (variable % 2 == 0) Material 89

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES {
cout<<variable<<“ is even number”;
}
else
{
cout<<variable<<“ is odd number”;
}
return 0;
}
Output
Enter Number: 5
5 is odd number
Enter Number: 8
8 is even number
Example 4.3: Write a program to print bigger number out of two input numbers.
#include <iostream>
using namespace std;
int main()
{
int value1, value2;
cout << “Enter two numeric Numbers: “ ;
cin>> value1 >> value2;
cout<<“two entered numbers are “<<value1 <<“
and “<<value2;
if (value1 > value2)
cout<<endl<< value1 <<“ is greater”;
else
cout<<endl<<value2 <<“ is greater”;
cout<< “ \n I am always executed”; // Statement is
always executed
return 0;
}
Self-Instructional
90 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

Output NOTES
Enter two numeric Numbers: 5
9
two entered numbers are 5 and 9
9 is greater
I am always executed

Explanation

In above code, curly braces are not present after if and else blocks which makes
only immediate statement to be executed depending on condition.

4.5 NESTED if STATEMENT

We have situations when one condition is placed inside another. For example if I buy
blue colour denim then I needs to buy black colour coat also. When we have hierarchy
of conditions, i.e., one condition inside another then nested if statements are used.
The structure of nested if statement is depicted below.
if (condition expression1)
{
if (condition expression2)
{

}
else
{

}
else
{
Self-Instructional
} Material 91

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES

Fig. 4.3 Flowchart for Nested if statement

Example 4.4: Write a program to find greatest of three numbers input from user.
#include <iostream>
using namespace std;
int main()
{
int variable1, variable2, variable3;
cout<<“Enter three numbers to be checked: “;
cin >> variable1>> variable2>> variable3 ;

Self-Instructional if(variable1>variable2)
92 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

{ NOTES
/* This is executed if num1 is greater than
num 2 */
if(variable1>variable3)
{
cout<<“Greatest Number is :”<<variable1;
}
else
{
cout<<“Greatest Number is :”<<variable3;
}
}
else
{
/* This is executed if num2 is greater than
num1 */
if(variable2>variable3)
{
cout<<“Greatest Number is :”<<variable2;
}
else
{
cout<<“Greatest Number is :”<<variable3;
}
}
return(0);
}
Output
Enter three numbers to be checked: 5
6
9
Greatest Number is : 9

Self-Instructional
Material 93

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
4.6 if-else-if LADDER

In some situations, user needs to make cascade of choices then if-else-if


ladder is used. Statements are executed from top if statement. While using if-else-
if statement we must remember the following points:
 if statement can be followed by zero or multiple else if statements, but
they must come before else statement
 else statement should always be placed last in if-else-if ladder
 statements are executed in top down manner, i.e., execution starts from first if
statement
 Starting from if statement at top, once one if condition evaluates to true,
rest all else if statements are bypassed. Last else block if present is also
not executed. But starting from top, if no condition evaluates to true, else
block is executed.
if (condition statement)
{
//executed only if condition statement evaluates to
true
}
else if (condition statement)
{
//executed only if condition statement evaluates to
true

Self-Instructional
94 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

NOTES

Fig. 4.4 Flowchart of if-else-if statement

Example 4.5: Generate bill of customer according to purchase done. If shopping is


more than 10000, then discount of 20% is given, if discount is less than 10000 but
more than 5000 then discount of 10% is given. If shopping is less than 5000 then
discount of 5% is applicable.
#include <iostream>
using namespace std;
int main() Self-Instructional
Material 95
{

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES float shopping_amount, final_price,discount;


cout << “Enter total shopping amount: “ ;
cin>> shopping_amount;
if (shopping_amount >= 10000)
{
cout<<“Discount of 20% was given”;
discount = 0.20 * shopping_amount;
cout<<discount;
final_price= shopping_amount - discount;
}
else if (shopping_amount < 10000 && shopping_amount
>=5000)
{
cout<<“Discount of 10% was given”;
discount = 0.10 * shopping_amount;
final_price= shopping_amount - discount;
}
else if (shopping_amount < 5000 )
{
cout<<“Discount of 5% was given”;
discount = 0.05 * shopping_amount;
final_price= shopping_amount - discount;
}
cout<<“\n The final price is: “<<final_price;
return 0;
}
Output
Enter total shopping amount: 5600
Discount of 10% was given
The final price is: 5040
Exercise
Write a program to generate report card of a student. Input marks of 5 subjects.
Calculate average. If average is greater than equal to 90%, grade O is awarded,
average between 80 to 90% grade A is awarded, average between 70 to 80% grade
Self-Instructional
96 Material B is awarded, average between 60 to 70% grade C is awarded, average between 50

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

to 60% grade D is awarded, average between 40 to 50% grade E is awarded, below NOTES
40% Fail.

4.7 switch STATEMENT

A switch statement is used to evaluate variable for equality for specified list of
values. Each value is checked in case statement, and the variable to be tested is checked
in switch expression. It is also used as an alternative to if-else-if ladder.
While using switch, following points must be followed:
 Expression in switch statement must evaluate to integer, character or
enumerated data type.
 Switch statement can have any number of case statements. Case statement
contains constant value to be compared and must be same data type of expression
in which switch evaluates to.
 Case statements are executed based on value of switch expression.
 Break statements are optional with case. If break statement is found,
switch terminates and flow of execution jumps to first statement after
switch. If no break is found, subsequent case statements are executed
until break is found.
 Default statement is optional and must appear at the end of switch
block. They are used for executing pieces of code when no condition in case
statements is met. Break statement is not used in default.
The structure of switch statement is as follows and the flowchart is depicted
in Figure 4.5.
switch (expression)
{
case value1:
statement(s);
break; //optional
case value2:
statement(s);
break; //optional Self-Instructional
case value3: Material 97

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES statement(s);
break; //optional
case value4:
statement(s);
break; //optional
default:
statement(s);
}

Self-Instructional
98 Material Fig. 4.5 Flowchart of switch

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

Example 4.6: Write a program to check if the entered character is a vowel or a NOTES
consonant.
#include <iostream>
using namespace std;
int main()
{
char character;
cout<<“Enter character to be checked: “;
cin>> character;
switch (character)
{
case ‘a’:
cout <<“It is a vowel”<<endl;
break;
case ‘e’:
cout <<“It is a vowel”<<endl;
case ‘i’:
cout <<“It is a vowel”<<endl;
case ‘o’:
cout <<“It is a vowel”<<endl;
case ‘u’:
cout <<“It is a vowel”<<endl;
default:
cout<<“It is a consonant”;

}
}
Output
Enter character to be checked: a
It is a vowel

Enter character to be checked: e


It is a vowel
Self-Instructional
It is a vowel Material 99

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES It is a vowel
It is a vowel
It is a consonant
In first output, since break is mentioned after case ‘a’, rest of the case
statements are skipped. In second output, no break statement in case ‘i’ was mentioned
which caused all subsequent case and default statement to be executed.
The difference between if-else and switch statement is given in Table 4.1.
Table 4.1 Difference between if-else and switch

if-else switch
Testing expression Can test expressions on Expression in switch statement
range of values must evaluate to integer, character
or enumerated data type
Readability In case of multiple If there are multiple conditions,
conditions, code is not switch provides much better
readable readability of code
Speed of execution Good for less than five Provides faster speed when there are
conditions five or more cases

Example 4.7: Write a program to build simple calculator using switch.


#include <iostream>
using namespace std;
int main()
{
int variable1, variable2;
char char_operator;
cout<<“Enter two numbers :”;
cin>> variable1>>variable2;
cout<<“Enter operator (+, -, *, /): “;
cin>> char_operator;
switch (char_operator)
{
case ‘+’:
cout << variable1 << “ + “ << variable2 << “
= “ << variable1 + variable2;
Self-Instructional
100 Material break;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

case ‘-’: NOTES


cout << variable1 << “ - “ << variable2 << “
= “ << variable1 - variable2;
break;
case ‘*’:
cout << variable1 << “ * “ << variable2 << “
= “ << variable1 * variable2;
break;
case ‘/’:
cout << variable1 << “ / “ << variable2 << “
=3 “ << variable1 / variable2;
break;

default:
cout<<“Operator is not correct”;

}
}
Output
Enter two numbers :5
9
Enter operator (+, -, *, /): *
5 * 9 = 45

4.8 CONDITIONAL OPERATOR

Conditional operator as discussed earlier can also replace if-else statement. The
structure of conditional operator is given below:
(Conditional Expression) ? Statement1:Stataement2

Statement1 is executed if condition Expression evaluates


to 1
Statement2 is executed if condition Expression
Self-Instructional
evaluates to 0 Material 101

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Example 4.8: Write a program to find greater of two numbers.


#include <iostream>
using namespace std;
int main()
{
int variable1, variable2;
char ch;
cout<<“Enter two numbers to be checked :”;
cin>> variable1>>variable2;
(variable1>variable2)? cout<<“number
“<<variable1<< “ is greater”: cout<<“number
“<<variable2<<“ is greater”;
}
Output
Enter two numbers to be checked :6
88
number 88 is greater

In-Text Questions
1. Which decision control statement is used to execute a block of code only if
the condition is true?
a) for loop
b) while loop
c) if statement
d) do-while loop
2. What is the syntax of the if statement in C++?
a) if (condition) { // code block }
b) if { // code block } (condition)
c) { // code block } if (condition)
d) { // code block } (condition) if
Self-Instructional
102 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

3. How many alternatives can an if-else statement have? NOTES


a) Only one alternative (if)
b) Two alternatives (if-else)
c) Multiple alternatives (if-else if-else)
d) Depends on the programmer’s choice
4. The switch statement works with which data types in C++?
a) int, char, and float
b) int, float, and string
c) int, char, and double
d) int, char, and bool
5. In a switch statement, if a case is matched, and there is no break
statement, what happens?
a) The program throws an error.
b) The program continues executing the code in the next case.
c) The program exits the switch statement.
d) The program executes the default case

4.9 SUMMARY

In the chapter on Decision and Control Statements in C++, we’ve delved into the
essential elements of control flow within C++ programming. These statements are the
foundation for creating programs that can make choices, repeat actions, and manage
the sequence of execution. We’ve explored conditional statements such as if, else if,
and else, gaining insight into crafting meaningful conditions using relational and logical
operators. The chapter also covered switch statements, which enable you to select
specific code blocks based on the value of an expression. Additionally, we’ve learned
about the various types of loops, including while, do-while, and for, and how to control
them with break and continue. The conditional operator was introduced as a concise
means to make choices in a single line of code. Throughout the chapter, the importance
of clean coding practices, like proper indentation, naming conventions, and informative Self-Instructional
Material 103

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES comments, was stressed. In essence, understanding decision and control statements is
pivotal for creating adaptable and efficient C++ programs, as they are the core constructs
for logic and flow control in the language.

4.10 GLOSSARY

 if Statement: A conditional control structure that allows you to execute a


block of code if a specified condition is true. It may include optional else if
and else blocks to handle multiple conditions.
 switch Statement: A multi-way branching control structure that selects
one of several code blocks to execute based on the value of an expression.
 for Loop: An iterative control structure used to repeat a block of code a
specific number of times. It consists of an initialization, a condition, and an
update statement.
 while Loop: A looping control structure that repeats a block of code as
long as a specified condition remains true. It is suitable for situations where the
number of iterations is not known in advance.
 do-while Loop: A looping control structure similar to the while loop,
but it guarantees at least one execution of the loop block because the condition
is checked after the loop body.
 Nested Loops: The practice of placing one loop inside another. This is used to
handle more complex control flow scenarios, especially for multi-dimensional
data structures or intricate iterative tasks.
 Break Statement: A control statement that allows you to prematurely exit a
loop or switch statement, usually based on a specific condition.
 Continue Statement: A control statement that causes the current iteration of a
loop to be skipped, and execution proceeds to the next iteration.
 Infinite Loop: A loop that runs indefinitely, as the loop condition never becomes
false. Creating an unintentional infinite loop can result in programs that do not
terminate and must be avoided.
Self-Instructional
104 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Decision Control Statements in C++

NOTES
4.11 ANSWERS TO IN-TEXT QUESTIONS

1. c) if statement
2. a) if (condition) { // code block }
3. c) Multiple alternatives (if-else if-else)
4. a) int, char, and float
5. b) The program continues executing the code in the next case.

4.12 SELF-ASSESSMENT QUESTIONS

Q1. What is the primary purpose of the if statement in C++, and how does it differ
from the else if and else blocks?
Q2. How does the switch statement differ from a series of if-else statements
in terms of control flow?
Q3. In a for loop, what are the three components: initialization, condition, and
update, and how do they work together?
Q4. When is the while loop typically used in C++ programming, and how does it
differ from a for loop?
Q5. Explain the key feature of a do-while loop and provide a scenario where it
might be more suitable than a while loop.
Q6. Describe the concept of nested loops and provide an example of a situation
where they would be beneficial.
Q7. How is the break statement used within a loop, and when might you use it?
Q8. Explain the purpose of the continue statement and provide an example of when
it can be valuable in a loop.
Q9. Why should you be cautious about creating infinite loops in your C++ programs,
and what measures can you take to prevent them?
Self-Instructional
Material 105

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Q10. Write a program to generate an electricity bill. Take number of consumed
units as input from the user. Criteria are as follows:
For the first 50 units 0.50/unit
For the next 100 units 0.75/unit
For the next 100 units 1.20/unit
For unit above 250 1.50/unit
An additional surcharge of 20% is added to the bill
Q11. Write a program to check if an individual is eligible to vote or not. Take age as
an input.
Q12. Write a program to check if the entered year is a leap year or not.

4.13 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


 Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented
programming with C++. Vol. 4. Tata McGraw-Hill, 2008

4.14 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
106 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

LESSON 5 NOTES

LOOPS IN C++

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
5.1 Learning Objectives
5.2 Introduction
5.3 for Loop
5.4 while Loop
5.5 do while Loop
5.6 Jump Statements
5.6.1 break
5.6.2 continue
5.6.3 goto
5.6.4 return
5.7 Summary
5.8 Glossary
5.9 Answers to In-Text Questions
5.10 Self-Assessment Questions
5.11 References
5.12 Suggested Readings

5.1 LEARNING OBJECTIVES

 To understand the use of loop statements in C++ such as for loop, while
loop and do while loop
 To explain the concept of jump statements such as break, continue, goto and
Self-Instructional
return Material 107

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
5.2 INTRODUCTION

In daily life, there are situations where we need to perform some operations again and
again until a condition is met. When the condition becomes false, we stop operation.
For example if we need to play a list of songs, we simply form a playlist. Now the
music player will keep on playing songs until the playlist is empty. For handling repeated
execution of statement(s) in C++, loops are used. For example if we need to execute
statement or block of statements more than once, we make use of loops in C++.
Loop statements used in C++ are as follows:
 for loop
 while loop
 do while loop
They are discussed one by one below.

5.3 for LOOP

for loop is the easiest loop in C++. It is used to execute statement(s) a fixed number
of times. for loop is used when we know in advance how many times statement(s)
need to be executed. The syntax of for loop is given below:
for(initialization; condition; iteration) // please
note no semicolon is present here
{
//statements to be executed
}
Initialization: Here initialization of variables occurs. Single or multiple variables can
be initialized here. Initialization expression is executed only once, at beginning of for
loop.

Self-Instructional
108 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Condition: If condition expression evaluates to true, body of loop is executed, if NOTES


evaluates to false body of loop is not executed and flow control of program is
transferred to next statement after for loop. Condition expression is evaluated before
execution of for loop body each time. If condition is met, then only body of for
loop is executed.
Iteration: It is used for updating value of initialized variable. Iteration expression is
evaluated after loop body executes.
Given below are some points to remember in for loop:
 Initialization, iterative and condition statements may or may not operate on same
variables.
 In initialization statement, variable declared is visible only inside for loop
body.
 Also if variable is defined inside for loop body, it can be accessed only inside
loop body. It is not accessible anywhere outside.
 If curly braces are not present after for loop, only next immediate statement is
executed if condition is met.
 Test expression needs to be checked thoroughly, if text conditions never goes
false infinite loop will occur.
 We can leave either one or all of the expressions of initialization, condition and
iteration.
There are two kinds of loops in C++, namely, entry controlled and exit controlled
loops. for and while loops are entry controlled loops whereas do while is
exit controlled loop.

Self-Instructional
Material 109

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES

Self-Instructional
110 Material Fig. 5.1 Flowchart of for loop

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Example 5.1: Write a program to print first n natural numbers. NOTES


#include <iostream>
using namespace std;

int main()
{
int num;

cout<<“Enter number :”;


cin>> num;

for (int i =1;i<=num;i++) //semicolon is not present


here
{
cout<<endl<<i; // body of loop
}

}
Output
Enter number : 5
1
2
3
4
5

Self-Instructional
Material 111

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Working of program


Iteration Variable Condition Action performed
i<=5
1 Variable i is declared 1<5 i=1
and initialized to 1 in true 1 is printed
initialization step; Control moves to iteration
expression and i is incremented
to 2
2 i=2 2<5 2 is printed
true Control moves to iteration
expression and i is incremented
to 3
3 i=3 3<5 3 is printed
true Control moves to iteration
expression and i is incremented
to 4
4 i=4 4<5 4 is printed
true Control moves to iteration
expression and i is incremented
to 5
5 i=5 5=5 5 is printed
true Control moves to iteration
expression and i is incremented
to 6
i=6 6 is neither equal Loop terminates
nor less than 5
false

Loop body is executed five times.


We can have multiple initialization and test expressions in for loop.
Example 5.2: Write a program with multiple initialization and test condition.
#include <iostream>
using namespace std;
int main()
{
int var1,var2;
for (var1=1,var2=1 ; var1<4 || var2<6;
var1++,var2++)
{
Self-Instructional
112 Material
cout<<var1 <<“ “<<var2<<endl;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

} NOTES
return 0;
}
Output
11
22
33
44
55
Working of program
Iteration Variable Condition Action performed
i<4 || j < 6
(i is less than 4 or j is less than 6)
1 Variable i 1<4 || 1< 6 i=1
and j are is true j=1
initialized to printed
1 Control moves to
iteration expression, i
and j are incremented
2 i=2 2<4 || 2< 6 i=2
j=2 true j=2
printed
Control moves to
iteration expression, i
and j are incremented
3 i=3 3<4 || 3< 6 i=3
j=3 true j=3
printed
Control moves to
iteration expression, i
and j are incremented
4 i=4 4<4 || 4< 6 i=4
j=4 true j=4
i and j are 4 printed
Control moves to
Test condition has two expressions iteration expression, i
First: i<4 and j are incremented
Second: j<6
Self-Instructional
Material 113

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES first condition 4<4 is false but since


we have or operator second
condition will also be checked
second condition 4<6 is true
so body of loop will execute
5 i=5 5<4 || 5< 6 i=5
j=5 true j=5
i and j are 5 printed
Control moves to
Test condition has two expressions iteration expression, i
First: i<4 and j are incremented
Second: j<6

first condition 5<4 is false but since


we have or operator second
condition will also be checked
second condition 5<6 is true
so body of loop will execute
6 i=6 6<4 || 6< 6 Loop terminates
j=6 false

Example 5.3: Write a program to illustrate infinite loop.


#include <iostream>
using namespace std;
int main () {
for (; ;)
cout<<“infinite for loop”; //when curly
braces are not used, immediate statement after for
loop is only executed as for loop body.

}
Output
infinite for loop
infinite for loop
infinite for loop
terminated forcefully
Explanation

Self-Instructional
When we omit test condition for loop, it will result in infinite loop
114 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Example NOTES
We can also nest one for loop inside another.
Example 5.4: Write a program that takes a positive integer n and produces n lines of
output as shown: (n=4 as output)
*
**
***
****
#include <iostream>
using namespace std;
int main()
{
int lines;
cout<<“Enter the lines “;
cin>> lines;
for (int p=1;p<= lines;p++)
{
for (int m=1;m<=p;m++)
{
cout<<“*”;
}
cout<<endl;
}

return 0;
}
Output
Enter the num4
*
**
***
Self-Instructional
Material 115

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Solved Exercise

1. Write a program to find sum of first n natural numbers.


#include <iostream>
using namespace std;
int main()
{
int var, sum =0;
cout<<“Enter the natural number till which sum is
required: “;
cin>>var;

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


{
sum += i;
}

cout <<“Sum of first “<<var<<“ natural numbers is:


“<<sum;
return 0;
}
Output
Enter the natural number till which sum is required: 5
Sum of first 5 natural numbers is: 15
2. Write a program to generate table of a given number.
#include <iostream>
using namespace std;
int main() {

int i, num;

cout<<“Enter number for which you want to print


table”;
Self-Instructional cin >>num;
116 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

cout<<endl<<“Table of “<<num<<“ is as follows:”; NOTES


for (i =1 ; i <=10; i++)
{
cout <<endl<<num <<“ * “ <<i <<“ = “<<num*i;
}
return 0;
}
Output
Enter number for which you want to print table5
Table of 5 is as follows:
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
3. Write a program to print square and cube of first n numbers.
#include <iostream>
using namespace std;
int main() {

int i, n;

cout<<“Enter number: “;
cin >>n;

cout<<endl<<“Number “ <<“ Square”<<“ Cube”; Self-Instructional


Material 117

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

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


{
cout <<endl<<i <<“\t\t”<< i*i <<“\t\t” << i*i*i;
}
return 0;
}
Output
Enter number: 5
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125

5.4 while LOOP

for loops are used, when we know in advance how many times loop needs to be
executed. But there are situations where number of times loop will execute is not
known, here while loops are used. Similar to the for loop, while loop is also
an entry controlled loop as whether the loop will execute or not is determined the by
test condition in entry phase.
Syntax of while loop is as follows:
while(test expression) // no semicolon is present
here

{
//statements to be executed
}
Initialization expression is present before while loop.
Self-Instructional
118 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Iteration expression is present inside for loop body. NOTES

Fig. 5.2 Flowchart of while loop


Self-Instructional
Some points to consider in while loop are as follows: Material 119

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  Test condition should be present in while loop.


 If there is only one statement in loop body, then braces can be omitted.
 Test condition can have more than 1 testing expression.
 while loop’s body is only evaluated if test condition is true.
Example 5.5: Write a program to generate factorial of a given number.
#include <iostream>
using namespace std;
int main() {

int i=1, n;
int fact=1;

cout<<“Enter number for which factorial needs to be


generated: “;
cin >>n;

while (i <= n)
{
fact = fact *i;
i++; //i variable is updated
}

cout<<“\n Factorial of “<<n<<“ is: “<<fact;


return 0;
}
Output
Enter number: 5
Factorial of 5 is: 120
Example 5.6: Write a program to demonstrate infinite while loop.
#include <iostream>
using namespace std;
int main() {
Self-Instructional
120 Material while (35<89)

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

{ NOTES
cout<<endl<<“infinite while loop”;
}
return 0;
}
Output
infinite loop
infinite loop
infinite loop
Forcefully terminated

Since 4<5 will always be true, it results in infinite loop.


Example 5.7: Write a program to print Fibonacci series up to n.
#include <iostream>
using namespace std;

void main()
{
int n, first, second, third ;
cout<<“Enter num: “;
cin>>n;

first =0;
second =1;
third = first + second;

cout<<endl<<“Fibonacci series is: “<<first <<“


“<<second;
while ( third <= n )
{
cout<<“ “<<third;
first = second;
Self-Instructional
second = third; Material 121

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES third= first + second;

}
Output
Enter num: 20
Fibonacci series is: 0 1 1 2 3 5 8 13

Solved Exercise

1. Write a program to accept a number, reverse it and print the sum of its digits.
#include <iostream>
using namespace std;

int main()
{
int num, nd, sum, rem,reverse_num=0;
cout<<“Enter a Number : “;
cin>>num;
nd = 0;
sum = 0;
while (num > 0)
{
rem = num % 10;
sum = sum+ rem;
num = num / 10;
reverse_num = reverse_num *10 + rem;

cout<<endl<<“The sum of digit is “<<sum;


cout<<endl<<“The reverse of digit is

Self-Instructional
122 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

“<<reverse_num; NOTES
return 0;
}
Output
Enter a Number : 1298
The sum of digit is 20
The reverse of digit is 8921

5.5 do while LOOP

In while loop, first condition is evaluated and if it is true then only the body is
executed. But there are situations where we want to execute the body of the loop
atleast once before condition statement is checked. Here do while loop is used.
do while loop is a variant of while loop where condition statement is evaluated
after execution of the body of the loop. It is an exit controlled loop, i.e., body of the
loop is executed first, and then condition expression is evaluated. If condition expression
evaluates to true, then body of the loop is executed again. In do while loop, body
of the loop is executed atleast once before the condition statement is met. The syntax
is as follows:
do
{

//body of loop

}while (condition);

Self-Instructional
Material 123

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES

Fig. 5.3 Flow Chart of do while loop

Self-Instructional
124 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Example 5.8: Write a program to find sum of positive numbers only. NOTES
#include <iostream>
using namespace std;

int main()
{
int num, sum_numbers;

sum_numbers =0;
num=0;
do {
sum_numbers += num;
cout<<“Enter Number: “;
cin>>num;
}while (num >=0);

cout<<“Sum is: “<<sum;


return 0;
}
Output
Enter Number: 5
Enter Number: 6
Enter Number: 7
Enter Number: -2
Sum is: 18
Example 5.9: Write a program to demonstrate infinite do while loop.
#include <iostream>
using namespace std;

int main()
{
int var =65;
Self-Instructional
do { Material 125

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout<<“\n In Infinite do while loop”;


}while (var >=0);
return 0;
}
Output
In Infinite do while loop
In Infinite do while loop
In Infinite do while loop
In Infinite do while loop
Forcefully Terminated

Solved Exercise

1. Write a menu driven program for following:


a. to check whether a given number is odd or even.
b. display a Fibonacci series
c. compute factorial of a number
#include <iostream>

using namespace std;

int main()
{
int choice, num;

do
{

cout<<endl<<“Menu is as follows.”;
cout<<endl<<“1. To check whether a given number
is odd or even”;
cout<<endl<<“2. Display a Fibonacci series”;
Self-Instructional cout<<endl<<“3. Compute factorial of a number”;
126 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

cout<<endl<<“4. Exit”; NOTES


cout<<endl<<“Please choose choice: “;
cin>>choice;

cout<<endl<<“Enter the number :”;


cin>>num;

switch (choice)
{
case 1: // print num is even or odd number
if (num % 2 ==0)
cout<<endl<<num <<“ is a even number”;
else
cout<<endl<<num <<“ is a odd number”;

break;
case 2: //print Fibonacci series
{
int first =0, second =1;
int third = first + second;

cout<<endl<<“Fibonacci series is:


“<<first <<“ “<<second;
while ( third <= num )
{
cout<<“ “<<third;

first = second;
second = third;
third= first + second;

}
break;
} Self-Instructional
Material 127

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES case 3: //print factorial of number


{
int i=1, fact =1;
while (i <= num)
{
fact = fact *i;
i++; //i variable is updated
}
cout<<“\n Factorial of “<<num<<“ is:
“<<fact;
break;
}
case 4: cout<<endl<<“Exit”;
break;

}while (choice != 4);

}
Output
Menu is as follows.
1. To check whether a given number is odd or even
2. Display a Fibonacci series
3. Compute factorial of a number
4. Exit
Please choose choice: 1

Enter the number : 3

3 is a odd number
Self-Instructional
128 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Menu is as follows. NOTES


1. To check whether a given number is odd or even
2. Display a Fibonacci series
3. Compute factorial of a number
4. Exit
Please choose choice: 2
Enter the number : 5
Fibonacci series is: 0 1 1 2 3 5
Menu is as follows.
1. To check whether a given number is odd or even
2. Display a Fibonacci series
3. Compute factorial of a number
4. Exit
Please choose choice: 3
Enter the number : 6

Factorial of 6 is: 720


Menu is as follows.
1. To check whether a given number is odd or even
2. Display a Fibonacci series
3. Compute factorial of a number
4. Exit
Please choose choice: 4
Enter the number :2
Exit
Notes:
 for loops are used when we know in advance how many times loop will Self-Instructional
execute. Material 129

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  while loop is used when condition has to be checked before executing the
loop body.
 do while loop is used when we need to execute the body atleast once
irrespective of the condition is met or not.

5.6 JUMP STATEMENTS

Sometimes we want to skip execution of a few statements and transfer control to


other parts in the program. For this purpose jump statements are used. There are four
jump statements which are given below.

5.6.1 break

These statements are used to terminate execution of loop. If break statement is


encountered in loop body, loop terminates and control is transferred to immediate
next statement after loop. They are used when a particular condition is met and there
is no use of executing rest of the loop.
Syntax is as follows:
break;
Example 5.10: Write a program to demonstrate the use of break statement.
#include <iostream>
using namespace std;

int main()
{
int num;
cout<<“Enter the variable: “ ;
cin>>num;

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


{
Self-Instructional if (i == 2)
130 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

{ NOTES
break;
}
cout<<“ “<<i;
}

cout<<endl<<“Outside for loop”;


}
Output
Enter the number: 5
01
Outside for loop

Explanation

As soon as break is encountered, control is transferred to next statement after loop.


Further loop iterations are not carried out.
Example 5.11: Write a program to evaluate if the entered number is prime or not.
#include <iostream>
using namespace std;
int main() {

int i, n;
bool is_prime = true;
cout << “Enter a numeric: “;
cin >> n;

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
is_prime = false;
}

// loop to check if n is prime


for (i = 2; i <= n/2; ++i) { Self-Instructional
Material 131

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES if (n % i == 0) {
is_prime = false;
break; //If a number is divisible by any number,
it is not checked further. With break statement control
is transferred out of loop skipping any further
iterations
}
}

if (is_prime)
cout << n << “ is a prime number”;
else
cout << n << “ is not a prime number”;

return 0;
}
Output
Enter a numeric: 6
6 is not a prime number

Explanation

Since prime numbers are divisible by 1 and itself


In statement for (i = 2; i <= n/2; ++i)
Initialization is done by 2,
Loop is checked only till half of entered number
Once number is found divisible by any number, it is not checked further. For this
break statement is used.

5.6.2 continue

Sometimes when a condition is met, we do not want to skip the entire loop, but
only that particular iteration. For this purpose continue statements are used. Instead
Self-Instructional
132 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

of transferring control to immediate next statements after loop, only that particular NOTES
iteration is skipped. Execution of the entire loop is not stopped, instead a particular
iteration where condition is met is skipped and the loop is resumed from next
iteration.
Syntax is as follows:
continue;
Example 5.12: Write a program to demonstrate continue statement.
#include <iostream>
using namespace std;

int main()
{
int num;
cout<<“Enter the number: “ ;
cin>>num;

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


{
if (i == 2)
{
continue;
}
cout<<“ “<<i;
}

cout<<endl<<“Outside for loop”;


}
Output
Enter the number: 9
01345678
Outside for loop

Self-Instructional
Material 133

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Explanation

Please see, only iteration for i==2 is skipped, and rest of loop executes as it is.

5.6.3 goto

The goto statement is used to transfer control of program from one statement to another
within same function.
Syntax is as follows:
goto label; //label is called
label: //label is defined
Example 5.13: Write a program to demonstrate the use of goto statement.
#include <iostream>

using namespace std;

int main()
{
int num;

cout<<“Enter the number: “ ;


cin>>num;

if (num % 2 == 0)
goto printeven; //label is called
else
cout<<endl <<“It is odd number”;

printeven: //label is defined


cout<<endl<<“It is even number”;
}
Output
Enter the number: 5
Self-Instructional
134 Material
It is odd number

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

Enter the number: 6 NOTES


It is even number

Explanation

If number is even, goto statement transfers control to printeven label.


If number is odd, simply cout statement in else part is executed.

5.6.4 return

This statement is used to return the control of a program or function. When the return
statement is encountered, the execution of program stops and the control is returned.
Also, it returns a value. For void function, no value is returned but for non-void functions
value must be returned.
Syntax is as follows:
return value;

Exercise

1. Write a program to find sum of all numbers between 200 and 300 which are
divisible by 7.
2. Write a program to print the series and its sum: 1 + 1/2! + 1/3! + … + 1/n!.
3. Write a C++ program to make a pattern of pyramid with an asterisk.
Sample Output:
Input number of rows: 4
*
* *
* * *
* * * *

Self-Instructional
Material 135

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
In-Text Questions
1. Which loop in C++ is used to execute a block of code repeatedly based on a
condition?
a) for loop b) while loop
c) do while loop d) if-else loop
2. What is the syntax of the for loop in C++?
a) for (initialize; condition; update) { // code
block }
b) for { // code block } (initialize; condition;
update)
c) { // code block } for (initialize; condition;
update)
d) for [initialize; condition; update] { // code
block }
3. How many times will a do while loop execute its code block if the condition
is false initially?
a) 0 times b) 1 time
c) At least once d) It depends on the loop body.
4. For what is the continue statement in a loop used?
a) Exit the loop entirely
b) Restart the loop from the beginning
c) Skip the current iteration and move to the next iteration
d) End the program execution
5. What happens if the condition is false initially in a while loop?
a) The loop will never execute.
b) The loop will execute indefinitely.
c) The loop will execute exactly once.
d) The loop will execute for a random number of times.
Self-Instructional
136 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

6. Which loop is more suitable when the number of iterations is known NOTES
beforehand?
a) for loop b) while loop
c) do while loop d) All loops are equally suitable
7. The for loop and the while loop can be used interchangeably. Is it true or
false?
a) True b) False
8. What does the break statement do in a loop?
a) Continues to the next iteration of the loop.
b) Exits the loop entirely.
c) Restarts the loop from the beginning.
d) Skips the current iteration and moves to the next iteration.
9. To what is the scope of the loop control variable limited in a for loop?
a) Limited to the loop body only b) Limited to the for statement only
c) Limited to the current function only d) Limited to the entire program
10. When is the condition in a do while loop checked?
a) Before executing the loop body.
b) After executing the loop body.
c) It is not possible to have a condition in a do while loop.
d) Do while loop does not require a condition.

5.7 SUMMARY

The chapter on loops in C++ delves into the critical aspect of control flow within
programming, enabling the repetition of specific code blocks. It introduces three primary
types of loops: the for loop, the while loop, and the do-while loop. The for
loop is an excellent choice for iterating over a known range of values and is often used
in counting or traversing arrays. The while loop continues execution as long as a
Self-Instructional
Material 137

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES given condition remains true, providing adaptability in loop control. The do-while
loop ensures at least one execution of the block, even if the condition is initially false.
These loops are instrumental in handling iterative tasks, processing data collections,
and implementing complex algorithms efficiently in C++ programs. Mastery of these
loop structures is crucial for writing organized and effective code, as they are fundamental
tools for managing control flow and automating repetitive tasks in C++.

5.8 GLOSSARY

 Loops: Control structures that allow a specific block of code to be executed


repeatedly, as long as certain conditions are met.
 for Loop: A type of loop that provides a compact and controlled way to
iterate through a range of values, often used for counting or traversing arrays.
 while Loop: A loop that continues execution as long as a specified condition
remains true, offering flexibility in loop control.
 do-while Loop: A loop that ensures at least one execution of the code
block, even if the condition is initially false, making it suitable for scenarios
where execution must occur before condition checking.
 Control Flow: The sequence in which statements and code blocks are executed
within a program, often determined by conditions and loops.
 Iterative Algorithms: Algorithms that involve repeating a specific set of
instructions or steps multiple times, typically achieved through the use of loops.

5.9 ANSWERS TO IN-TEXT QUESTIONS

1. b) while loop
2. a) for (initialize; condition; update) { // code
block }
3. c) At least once
Self-Instructional
138 Material 4. c) Skip the current iteration and move to the next iteration

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Loops in C++

5. a) The loop will never execute. NOTES


6. a) for loop
7. a) True
8. b) Exits the loop entirely
9. a) Limited to the loop body only
10. b) After executing the loop body

5.10 SELF-ASSESSMENT QUESTIONS

Q1. Explain the differences between the for loop, while loop, and do-while
loop in C++. When would you choose one over the other for a particular
programming task?
Q2. How does the concept of loop control variables play a role in managing loops?
Provide an example of a situation where a loop control variable is used effectively.
Q3. What are the potential risks associated with infinite loops, and how can they be
avoided when using loops in C++? Provide an example of a scenario where an
infinite loop might occur.
Q4. In what types of programming scenarios are iterative algorithms commonly used,
and how do loops facilitate the implementation of these algorithms in C++?
Q5. Write a C++ program that uses a for loop to print all even numbers between
1 and 20.
Q6. Create a C++ program that utilizes a while loop to calculate the factorial of
a given positive integer entered by the user.

5.11 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


 Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented
Self-Instructional
programming with C++. Vol. 4. Tata McGraw-Hill, 2008 Material 139

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
5.12 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
140 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
UNIT IV: ARRAYS, POINTERS AND USER
DEFINED FUNCTIONS

LESSON 6 FUNCTIONS IN C++

LESSON 7 ARRAYS AND POINTERS IN C++


Functions in C++

LESSON 6 NOTES

FUNCTIONS IN C++

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
6.1 Learning Objectives
6.2 Introduction
6.3 Uses of Functions
6.4 Types of Functions
6.4.1 Built-in Functions
6.4.2 User Defined Functions
6.5 Call Methods in Function
6.6 Function Overloading
6.7 Default Arguments
6.7.1 Ambiguity in Function Overloading When Done Using Default
Arguments
6.8 Return by Reference
6.9 Solved Exercise
6.10 Summary
6.11 Glossary
6.12 Answers to In-Text Questions
6.13 Self-Assessment Questions
6.14 References
6.15 Suggested Readings

6.1 LEARNING OBJECTIVES

 To understand built-in and user-defined functions in C++ Self-Instructional


Material 143

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  To explain the overview of call by methods


 To discuss the concept of function overloading, default arguments and return by
reference

6.2 INTRODUCTION

Block of code or group of statements which are used to perform specified tasks is
termed as function in C++. Functions can be used again and again during the life time
of a program.
Syntax of functions is as follows:
return_type function_name (parameter 1, parameter
2, ….)
{
//body
}
Return type specifies data type of value function will return. If return type is
void, functions do not return anything else they return value.
Function name specifies the name of function by which it is called.
Parameters are arguments given to a function. A function can have zero or more
arguments.
Task assigned to a function is performed in the body of the function.
Example 6.1: Write a function to calculate the area of a circle.
#include <iostream>
using namespace std;
float area_circle (float radius); //declaration of
function
int main()
{
float radius, result;
cout <<“Enter the radius of circle: “;
cin>>radius;
Self-Instructional
144 Material result=area_circle(radius); //function is called

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

cout<<endl<<“Area is: “<<result; NOTES


}
float area_circle (float radius) //definition of
function
{
float area;
cout<<endl<<“I am in function”;
area= 3.14 * radius * radius;
return area;
}
Output
Enter the radius of circle: 4
I am in function
Area is: 50.24

Explanation
float area_circle (float radius);
This statement is function declaration.
Function declaration constitutes, return type, function name and parameters
inside brackets. Parameters name may or may not be specified. Function declaration
is also termed as signature statement of function.
If we are defining function after it is being called in main function, then we need
to specify function declaration before. That means function declaration can be skipped
altogether if we are defining function before it is being invoked.
result=area_circle(radius);
In this statement function is being called or invoked inside main. By this statement
control of program is transferred to part of program where function is defined. And
after function body is executed again control returns back to this statement and value
is returned in result. Function can be invoked any number of times.
float area_circle (float radius) //definition of
function
{
Self-Instructional
float area; Material 145

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout<<endl<<“I am in function”;


area= 3.14 * radius * radius;
return area;
}
Above block defines function. It specifies task function needs to perform.
float area_circle (float radius)
First float specifies return type of function i.e., data type of returning value.
area_circle is name of function
Second float is data type of parameter radius.
Function can have zero or more paramters.
Return type can be void or any other valid data type. If return type is void,
function need not return any value.

6.3 USES OF FUNCTIONS

Some uses of functions are given below:


 Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in maintenance
as we have to make changes in only one place if we make changes to the
functionality in future.
 Functions make code modular. Consider a big file having many lines of code. It
becomes really simple to read and use the code,if the code is divided into
functions.
 Functions provide abstraction. For example, we can use library functions without
worrying about their internal work.

6.4 TYPES OF FUNCTIONS

Self-Instructional There are two types of functions in C++ as shown in Figure 6.1.
146 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

NOTES

Fig. 6.1 Types of Functions in C++

6.4.1 Built-in Functions

Built-in functions also known as library functions are already present in C++. Their
definitions are picked up from header files used in a program. sqrt(), abs(),
setw(), isdigit() are some of the common library functions available in
C++. To use library function in a program, corresponding header file is included in the
program and the function is called. User does not write the definition of function,
compiler automatically picks up the definition from header file.
Example 6.2: Write a program to demonstrate the use of built-in functions.
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
float number, square_root;
cout<<“Enter the Number: “;
cin>>number;

square_root = sqrt(number);

cout<<endl<<“Square Root of number is


:”<<square_root;
}
Output
Enter the Number: 25
Self-Instructional
Square Root of number is :5 Material 147

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Explanation

sqrt is library function defined in cmath header file.


square_root = sqrt(number);
In the above line, sqrt is simply called.
Example 6.3: Write a program to demonstrate the use of built-in functions.
#include <iostream>
#include<cmath>
using namespace std;
int main()
{
char ch;
cout<<“Enter the character: “;
cin>>ch;

if (isdigit(ch))
{
cout<<endl<<ch<<“ is a digit”;
}
else
{
cout<<endl<<ch<<“ is a character”;
}
}
Output
Enter the character: 9
9 is a digit

6.4.2 User Defined Functions

Functions that are defined by the user are termed as user defined functions. They can
be further divided as given below:
Self-Instructional
148 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

 No return value and has no parameters: The functions which have no return NOTES
type and do not take any arguments as inputs come in this category. Return type
void is for such functions.
 No parameters but has return value: No arguments are passed to the
function, but there is a return value.
 Parameters but no return value: The function has arguments, but there is no
return value, i.e., it has void return type.
 Argument and return value: The function has both arguments and returns
value.
Example 6.4: Write a program for function having no return value and no parameter.
#include <iostream>
#include<cmath>
using namespace std;

void func ();


int main()
{
cout<<“Hi!! I am in main “;

func();
}

void func(void) //Writing void in arguments is optional.


Specifies function has no parameters
{
cout<<endl<<“Hi i am in function”;
}
Output
Hi!! I am in main
Hi i am in function

Self-Instructional
Material 149

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Explanation

func has no return type and does not take any input arguments
Example 6.5: Write a program to calculate the area of a rectangle and demonstrate
function having return value and parameters.
#include <iostream>
#include<cmath>
using namespace std;

int area (int,int); //Function declaration


int main()
{
int side1,side2, result;
cout<<“Enter the sides of rectangle “;
cin>>side1>>side2;

result=area(side1,side2); //calling
cout<<endl<<“Area of rectangle is: “<<result;
}

int area( int x, int y) //Definition


{
int result;
result = x * y;
return result;
}
Output
Enter the sides of rectangle 4
8
Area of rectangle is: 32

Explanation
int area (int, int); //Function declaration
Self-Instructional
150 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

Above statement is function declaration. NOTES


Please note that the name of parameters can be omitted in declaration.

result=area(side1,side2);
side1 and side2 are parameters passed to function. Please note data type of
parameters passed matches to that of parameters in function declaration and definition.
Parameters passed to function are also known as actual parameters. Here side1,
side2 are actual parameters.

int area( int x, int y) //Definition


Here also data type of parameters matches to that of parameters in function
declaration
Parameters received by function are known as formal parameters. Here x and
y are formal parameters.

Inline Functions

Inline functions are also defined by the user but they vary with other user defined
functions in terms of the execution behaviour. They are offered by C++ to minimize the
overhead associated with the behaviour of function calling. The “inline” keyword is
used to make a function inline and should be defined above the main function.
The syntax of the inline function is as follows:
inline return-type function-name(parameters) {
//function body
}
Example 6.6: Write a program to demonstrate the inline function.
#include <iostream>

using namespace std;

inline int square(int num) { return num*num; }


int main() Self-Instructional
Material 151

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES {
cout<<“The square of 3 is “<<square(3);
return 0;
}
Output
The square of 3 is 9

Explanation

The square function is an inline function. While execution, the control is not transferred
to the square function, because compiler will replace the function call of square in
cout statement of main function with its body. We can call the main function as
calling function, and square function as called function.
The behaviour of simple user-defined function and inline function is defined as follows:
 Simple user-defined function: When a function call is encountered by the
calling function, some extra processing is done by the system. The control is
first transferred to the called function, and after execution of the called function,
the control is transferred back to the calling function. This extra processing for
control transfer is treated as overhead.
 User-defined inline function: Instead of transferring control to the calling
function, the body of the calling function replaces the function call.
The main advantage of using an inline function is the fast execution as compared to
other function. The execution becomes fast as there is no overhead of controlling
transfer to the calling function. We can make a simple and short function as inline, but
we cannot make a function inline if the function is of following types:
 Containing loop, or static variable
 Recursive function
 Return type is void
 Contains goto or switch statement

Self-Instructional
152 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

NOTES
6.5 CALL METHODS IN FUNCTION

Function can be invoked in two ways as given below:


 Call by Value: In call by value method, value of actual parameters are passed
to formal parameters. Both actual and formal parameters are stored at different
memory locations. Change in the value of formal parameters is not reflected in
the value of actual parameters. Only copies of variables are passed. Any changes
done in the values of variables in called function do not affect their value in the
main function.
Example 6.7: Write a program to demonstrate call by value. This program also takes
two arguments and has no return value.
#include <iostream>
using namespace std;

void swap (int, int); //Function declaration


int main()
{
int num1,num2;
cout<<“Enter the two numbers: “;
cin>>num1>>num2;

swap(num1,num2); //actual parameters


cout<<endl<<“In main function”;
cout<<endl<<“Numbers are: “<<num1<<“ “<<num2;
}

void swap( int x, int y) //Definition. x and y are


formal parameters
{
int temp;
temp=x;
x=y;
y=temp; Self-Instructional
Material 153

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout<<endl<<“In swap function”;


cout<<endl<<“Numbers are: “<<x<<“ “<<y;

}
Output
Enter the two numbers: 4
6
In swap function
Numbers are: 6 4
In main function
Numbers are: 4 6

Explanation
swap(num1,num2); //actual parameters
In above statement, actual parameters num1 and num2 of swap function are
having value 4 and 6
When function swap is called, x and y formal parameters receive value 4 and 6.
x and y occupy different memory locations then actual parameters num1 and num2. x
and y also receive values as 4 and 6.
After swapping of values on x and y variables in swap function, now x and y
have values 6 and 4 respectively. The same is also printed.
Any change made in the value in formal parameters x and y will not reflect in
actual parameters. Scope of variables x and y are limited to function swap. When we
move back to main function, scope of x and y is terminated.
When control moves back to the main function, values of num1 and num2 are 4 and 6
respectively.
 Call by Reference: In call by reference method, address of actual parameters
is passed to formal parameters. Both actual and formal parameters share same
memory locations. That means any change in the value of formal parameters
will be reflected in the value of actual parameters.
Self-Instructional
154 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

Example 6.8: Write a program to demonstrate call by reference. NOTES


#include <iostream>
using namespace std;

void swap (int &x,int &y); //Function declaration


int main()
{
int num1,num2;
cout<<“Enter the two numbers: “;
cin>>num1>>num2;

swap(num1,num2);
cout<<endl<<“In main function”;
cout<<endl<<“Numbers are: “<<num1<<“ “<<num2;
}

void swap( int &x, int &y) //call by reference


{
int temp;
temp=x;
x=y;
y=temp;
cout<<endl<<“In swap function”;
cout<<endl<<“Numbers are: “<<x<<“ “<<y;

}
Output
Enter the two numbers: 4
7
In swap function
Numbers are: 7 4
In main function
Self-Instructional
Numbers are: 7 4 Material 155

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES void swap (int &x, int &y); //Function declaration


Above statement denotes method will be invoked by call by reference method
Reference of variables i.e., memory locations at which they are stored are passed
using & sign
swap(num1,num2);
Address locations of num1 and num2 is passed to x and y. That means x starts
pointing to memory location of num1 and y starts pointing to memory location of
num2.
This implies variables num1 and x are sharing same memory locations. Same is
case with variables num2 and y. So any change done in value of x will be reflected in
value of num1. Similarly change in value of num2 is reflected in value of y.
After swap function is called, changes in value of x and y are also reflected in
values of num1 and num2 in main function. Thus values of num1 and num2 are swapped
in main function.
Difference between call by value and call by reference methods are given in
Table 6.1.
Table 6.1 Difference between Call by Value and Call by Reference

Call by Value Call by Reference


Copy of actual parameters are passed to Address of actual parameters is passed to
formal parameters formal parameters.
Change in value of formal parameters is Change in value of formal parameters is
limited to scope of function also reflected outside function
Actual and formal arguments are created Actual and formal arguments refer to
in different memory location same memory location.

6.6 FUNCTION OVERLOADING

When two or more functions have same name but number or data type of parameters
differ, then it is known as function overloading. Functions overloaded may or may not
have same return data type, but the number of parameters must differ in number or
data type.
Self-Instructional
156 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

int area(int a) { } NOTES


int area(int a, int b) { }
float area(double a) { }
All these three functions are examples of function overloading.
In first function int area(int a) { }
Only single int value is passed as argument.

int area(int a, int b) { }


Two int values are passed.

float area(double a) { }
Float Data type value is passed.

Thus either number of parameters vary or data type of parameter vary.

Example 6.9: Write a program to demonstrate function overloading.


#include <iostream>
using namespace std;

int area(int, int);


int area(int); //
float area(float);

int main()
{
int side1,side2;
float radius, result;
int ch;

do Self-Instructional
{ Material 157

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout<<endl<<“Menu for calculating Area”;


cout<<endl<<“Choose 1 for Area of circle”;
cout<<endl<<“Choose 2 for Area of square”;
cout<<endl<<“Choose 3 for Area of rectangle”;
cout<<endl<<“Choose 4 for Exit”;

cout<<endl<<“Enter Choice: “;
cin>>ch;

switch (ch)
{
case 1:
{
cout<<“Enter the radius: “;
cin>> radius;
result = area(radius);
cout<<endl<<“Area of circle is
:”<<result;
}
break;
case 2:
{
cout<<“Enter the side: “;
cin>> side1;
result= area(side1);
cout<<endl<<“Area of square is
:”<<result;
}
break;
case 3:
{
cout<<“Enter the two sides :”;
cin>> side1>>side2;
result= area(side1,side2);
Self-Instructional cout<<endl<<“Area of rectangle is :”<<
158 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

result; NOTES
}
break;
default:
cout<<endl<<“Wrong choice”;
break;
}
}while(ch != 4);
}

int area(int side)


{
int result;
cout<<endl<<“I am in function with one argument
of int data type”;
result = side * side;
return result;

int area(int side1, int side2)


{
int result;
cout<<endl<<“I am in function with two argument
of int data type”;
result = side1 * side2;
return result;

float area(float radius)


{
float result;
cout<<endl<<“I am in function with one argument Self-Instructional
Material 159

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES of float data type”;


result = 3.14 * radius * radius;
return result;
}
Menu for calculating Area
Choose 1 for Area of circle
Choose 2 for Area of square
Choose 3 for Area of rectangle
Choose 4 for Exit
Enter Choice: 1
Enter the radius: 122

I am in function with one argument of float data type


Area of circle is : 452.16
Menu for calculating Area
Choose 1 for Area of circle
Choose 2 for Area of square
Choose 3 for Area of rectangle
Choose 4 for Exit
Enter Choice: 2
Enter the side: 5

I am in function with one argument of int data type


Area of square is : 25
Menu for calculating Area
Choose 1 for Area of circle
Choose 2 for Area of square
Self-Instructional Choose 3 for Area of rectangle
160 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

Choose 4 for Exit NOTES


Enter Choice: 3
Enter the two sides :5
6

I am in function with two arguments of int data type


Area of rectangle is :30
Menu for calculating Area
Choose 1 for Area of circle
Choose 2 for Area of square
Choose 3 for Area of rectangle
Choose 4 for Exit
Enter Choice: 4

Wrong choice

Explanation
int area(int, int);
int area(int);
float area(float);
This is an example of function overloading as three functions have same name
area and they have different parameters or data type of parameters differs.
int area(int, int);
This function has two parameters.
int area(int);
This function has one parameter.
Self-Instructional
Material 161

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES float area(float);


In this function data type is different.

int area(int);
float area(float);
Above statements are examples of function overloading with different data types
of parameters.
int area(int, int);
int area(int);
Above statements are examples of function overloading with different number
of parameters.

6.7 DEFAULT ARGUMENTS

When values are assigned to parameters or arguments in function definition, then those
arguments are termed as default arguments. When value is not passed to default
arguments while call to function is made, then compiler automatically uses default
values. And when values are passed to the parameters during call to function, default
arguments are overridden.
Example 6.10: Write a program to demonstrate default arguments in functions.
#include <iostream>
using namespace std;

float average(float a,float b, float c=5, float d=6,


float e=7);
int main()
{
float result;
result = average (2,5);
cout<<endl << “Average of numbers is: “<<result;

Self-Instructional
162 Material
result = average (2,5, 6);

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

cout<<endl << “Average of numbers is: “<<result; NOTES

result = average (2,5, 6, 8);


cout<<endl << “Average of numbers is: “<<result;
}

float average (float a, float b, float c, float d,


float e)
{
float result;

result = (a + b + c + d + e) / 5;

return result;
}
Output

Average of numbers is: 5


Average of numbers is: 5.2
Average of numbers is: 5.6
When statement result = average (2,5);
Is called default values to c, d and e are passed
When statement result = average (2,5, 6);
Is called, default values to d and e are passed
When statement result = average (2,5, 6,8);
Is called, default values to e is only passed
Some points to consider in default arguments are as follows:
 Values assigned to default arguments are not constant. These values are
overwritten if values are passed by calling function.
 Arguments that are given default values are placed on right, i.e., if default value
is assigned to parameter, all subsequent parameters should be assigned default Self-Instructional
values. Material 163

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  If value of default parameters is defined in definition instead of function declaration,


then definition should be placed before calling function.
Some examples of Invalid syntax in default arguments are given below:
// Invalid
void sum(int x, int y = 3, int z);

// Valid
void sum(int x, int y, int z = 3);

// Invalid code

int main() {
show();
}

void show (char c = ‘$’, int count = 2) {


// code
}

6.7.1 Ambiguity in Function Overloading When Done Using Default


Arguments

When we are doing function overloading and using default parameters, we should see
that compiler should not get confused while calling, which function is to be called.
Example 6.11: Write a program to demonstrate Ambiguity in function overloading
when done using default arguments.
#include<iostream>
using namespace std;
int add(int a,int b, int c=10) // c int is default
parameter
{
return (a + b + c);
Self-Instructional
}
164 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

int add(int a, int b, float c=0) //// c float is NOTES


default parameter
{
return (a + b + c);
}
int main()
{
cout << add(10, 15) << endl;
cout << add(10, 15, 25) << endl;
return 0;
}
Error
main.cpp: In function ‘int main()’:
main.cpp:13:16: error: call of overloaded ‘add(int, int)’ is ambiguous
13 | cout << add(10, 15) << endl;
| ~~~^~~~~~~~
main.cpp:3:5: note: candidate: ‘int add(int, int, int)’
3 | int add(int a, int b, int c=10) // c int is default parameter
| ^~~
main.cpp:7:5: note: candidate: ‘int add(int, int, float)’
7 | int add(int a, int b, float c=0) //// c float is default parameter
| ^~~

6.8 RETURN BY REFERENCE

We have discussed how to pass value to arguments by reference, here we will learn
how we can return value by reference.
Example 6.12: Write a program, to demonstrate return by reference.
#include <iostream>
using namespace std; Self-Instructional
Material 165

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
int test_variable; //global varaible

// function declaration
int& test_function();

int main() {

// reference to varible is returned and value is


assigned
test_function() = 10;

cout << test_variable;

return 0;
}

// function definition
// returns the address of int variable
int& test_function() {
return test_variable;
}
Output
10
Return type of function is int&. It returns reference to variable, i.e., address
of variable.
Please make note test_function() is placed on left as compared to
other places where call to function is always placed on right.
Here, in the function definition, reference to variable is returned so variable can
be assigned a value. It is same as writing variable = 10;
Some important points to consider while using returning by reference are as follows:
 Normal functions return values, but here we are returning reference to variable.
Self-Instructional So a constant value can not be returned from this function.
166 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

 Since the scope of local variables is only within function, so we cannot return NOTES
reference to local variable from these functions. As soon as the function called is
returned, local variables are removed from the stack, so reference to global
variables are returned from these functions.
Some invalid code examples while using return by reference
int& test_function() {
return 10;
}
Explanation: Constant value is being returned. So the code written above is an invalid
code.
int& test_fuinction() {
int x = 10;
return x;
}
Explanation: Reference to local variables can not be returned. So the code written
above is an invalid code.

6.9 SOLVED EXERCISE

1. Write a program using functions to print the series and its sum: 1 + 1/2! + 1/3!
+ … + 1/n!.
#include <iostream>
using namespace std;
int factorial(int);
float series_sum(int);

int main()
{
int n;
cout<<“Enter the number: “;
cin>> n;
Self-Instructional
Material 167
cout<< endl<<“Series sum is :”<< series_sum(n);

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES }

float series_sum(int x)
{
float sum=0;
int i=1;
while(i<=x)
{

sum += (float)1 / factorial(i); //To get


answer in floating point, 1 is typecasted to float
i++;
}
return sum;
}

int factorial(int x)
{
int fact =1;
int i=1;
while(i<=x)
{
fact *= i;
i++;
}
return fact;
}
Output
Enter the number: 5
Series sum is :1.71667
Explanation
The factorial function is called from within series_sum function.

Self-Instructional
The sum of series is obtained and returned back to the main function.
168 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

NOTES
In-Text Questions
1. Functions in C++ are used for:
a) Controlling the flow of the program
b) Defining classes and objects
c) Grouping and organizing code for reusability
d) Handling exceptions and errors
2. The return type of a C++ function can be:
a) Only integers
b) Any data type, including user-defined types
c) Only built-in data types (int, char, etc.)
d) Only float and double
3. What is the keyword used to define a function in C++?
a) func b) function
c) method d) void
4. The process of passing arguments by reference in a function allows:
a) Reducing the number of arguments passed to the function
b) Modifying the original values of the arguments inside the function
c) Enabling the function to return multiple values
d) Reducing the function's execution time
5. A function prototype in C++ is used for:
a) Specifying the return type of the function
b) Providing a function declaration before its actual definition
c) Declaring a function that takes no arguments
d) Defining a function within another function
6. What is the default return type of a function in C++ if it is not specified?
a) int b) void
c) float d) char

Self-Instructional
Material 169

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
6.10 SUMMARY

Functions in C++ are fundamental building blocks for organizing and reusing code.
They enable you to encapsulate a set of instructions into a named block, making code
more modular and readable. C++ functions consist of a function signature, which
defines the function’s name, return type, and parameters, along with a function body
containing the code to be executed. You can declare functions before their use, and
the actual implementation can be defined separately. Functions can accept parameters,
allowing data to be passed into the function, and can return values as a result. This
chapter covers function creation, parameter passing, return values, function overloading,
and the use of standard library functions, emphasizing the role of functions in code
organization, reusability, and the development of efficient and maintainable C++
programs.

6.11 GLOSSARY

 Function Declaration: It consists of its name, return type, and parameter list,
defining its interface and how it can be called.
 Function Body: The part of a function that contains the actual code to be
executed when the function is called.
 Parameter: A variable used within a function to accept data passed into the
function during its invocation, allowing for flexibility and reusability of the code.
 Return Value: The value that a function can optionally return to the calling
code, conveying the result of the function’s execution.
 Function Overloading: A feature in C++ that allows you to define multiple
functions with the same name but different parameter lists, providing flexibility in
function usage and enabling polymorphism in the language.

Self-Instructional
170 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Functions in C++

NOTES
6.12 ANSWERS TO IN-TEXT QUESTIONS

1. c) Grouping and organizing code for reusability


2. b) Any data type, including user-defined types
3. d) void
4. b) Modifying the original values of the arguments inside the function
5. b) Providing a function declaration before its actual definition
6. a) int

6.13 SELF-ASSESSMENT QUESTIONS

Q1. How can functions in C++ be used to encapsulate and modularize code, and
what are the advantages of doing so?
Q2. How are member functions in C++ classes utilized to model and manipulate
objects, and what benefits do they provide in object-oriented programming?
Q3. Write a menu driven program for the following:
a. to check whether a given number is odd or even.
b. display a Fibonacci series
c. compute factorial of a number
Perform these operations by calling functions.
Q4. Write a program to accept a number, reverse it and print the sum of its digits.
Reversal and sum of digits should be implemented in different functions.

6.14 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


Self-Instructional
Material 171

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented


programming with C++. Vol. 4. Tata McGraw-Hill, 2008

6.15 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
172 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

LESSON 7 NOTES

ARRAYS AND POINTERS IN C++

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
7.1 Learning Objectives
7.2 Introduction of Arrays
7.3 Initialization and Declaration of Array
7.3.1 Initializing Values to Array during Declaration
7.3.2 Assigning Values to Array after Declaration
7.4 Types of Array in C++
7.4.1 Single Dimensional Array
7.4.2 Multi-Dimensional Array
7.5 Passing Array to Function
7.6 Pointers
7.7 Pointer- Declaration and Initialization
7.8 Solved Exercise
7.9 Summary
7.10 Glossary
7.11 Answers to In-Text Questions
7.12 Self-Assessment Questions
7.13 References
7.14 Suggested Readings

7.1 LEARNING OBJECTIVES

 To understand the meaning of arrays


 To discuss the initialization, declaration and types of arrays Self-Instructional
Material 173

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES  To analyse the method of passing array to function


 To explain the concept of pointers

7.2 INTRODUCTION OF ARRAYS

Array is the collection of homogeneous data items which are stored continuously in
memory. In simple words we can define array as a group of similar items which are
stored one after another in memory. Similar items which occupy continuous memory
space are termed as array. It is the most used data type in C++.

Fig. 7.1 Array Representation in Memory

In Figure 7.1, similar data items, i.e., int data type elements (7, 10, 2, 23, 12, 6)
are stored in adjacent memory locations and can be accessed by 0, 1, 2, 3, 4, 5 array
index. By default in C++, array index starts from 0 and goes till the size of array -1. In
Figure 7.1, there are total 6 elements in array. We can have array of any data type like
int, float, char, etc.

7.3 INITIALIZATION AND DECLARATION OF ARRAY

For declaration of array in C++, we need to have data type of elements, name and
size of array. Basic syntax is represented below:
data_type array_name [size];
Example7.1: int num[5];

Self-Instructional
174 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

Explanation NOTES

 num is name of array. 5 is size of array and data type of num array is int. 5
int data type variables are stored together in memory.
 Array elements are accessed by index. For example here array elements will be
accessed from index 0…. to 4. They are accessed like num[0],
num[1]……., num[4].
 First element of array is stored at index 0 and can be accessed by using num[0],
similarly last element can be used by accessing num[4].
 Array elements are stored continuously in memory. For example
If size of int data type is 4 bytes in memory,
First element of array num[0] is stored at 1000 memory location,
num[1] will be stored at 1004
num[2] will be stored at 1008
num[3] will be stored at 1012
last element num[4] will be stored at 1016
 Here num array contains 5 elements and from index 0 to 4. If we try to access
5th element we will get “out of bound error”.
Initialization of arrays in C++ can be done in two ways as given below:
 Initializing values to array during declaration
 Assigning values to array after declaration
These two ways are described below.

7.3.1 Initializing Values to Array during Declaration

Here values are assigned to array during declaration phase only.


Example 7.2: int x[5] = {18, 23, 5, 6, 89};

Explanation

Array of name x , data type int has 5 elements and has been assigned values and they
Self-Instructional
can be accessed in following way Material 175

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES x[0]=18
x[1]=23
x[2]=5
x[3]=6
x[4]=89
Example 7.3: int x[] = {18, 23, 5, 6, 89};
Explanation
Array of name x , data type int has been assigned values and they can be accessed in
the following way:
x[0]=18
x[1]=23
x[2]=5
x[3]=6
x[4]=89
Size of array is not assigned. But compiler automatically computes the size
depending on the values assigned.

7.3.2 Assigning Values to Array after Declaration

Here, an array is simply declared, i.e., data type and size of the array is defined. The
values are assigned at a later stage.
Example 7.4: Write a program to enter and display array elements.
#include <iostream>
using namespace std;
int main()
{
int num[5];
cout << “Enter the elements of array: “;
for (int i=0;i<5;i++) //loop for input of array
elements
Self-Instructional cin>>num[i];
176 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

NOTES
cout << “Print the elements of array: “;
for (int i=0;i<5;i++) //loop for display of array
elements
cout<<endl<<“num[“<<i<<“]: “<<num[i];

return 0;
}
Output
Enter the elements of array: 5
1
6
45
89
Print the elements of array:
num[0]: 5
num[1]: 1
num[2]: 6
num[3]: 45
num[4]: 89

Explanation
int num[5];
In the above statement, num array of data type int and size 5 is declared.
Values are not assigned.

for (int i=0;i<5;i++) //loop for input of array


elements
cin>>num[i];
In this, for loop is used to assign values to array indexes.
Self-Instructional
Material 177

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES for (int i=0;i<5;i++) //loop for display of array


elements
cout<<endl<<“num[“<<i<<“]: “<<num[i];
In this, for loop is used to print values assigned at various array indexes.

7.4 TYPES OF ARRAY IN C++

There are two types of array in C++, viz., single dimensional array and multi-dimensional
array.

7.4.1 Single Dimensional Array

Arrays in which elements are stored in single dimension are termed as single dimensional
arrays.
The syntax is as follows:
data_type array_name[size];
float num[5];
Single dimensional array is represented in Figure 7.2.

Fig. 7.2 Single Dimensional Array

Example 7.5: Write a program to calculate sum and average of array elements.
/* Online C++ Compiler and Editor */
#include <iostream>

using namespace std;

int main()
{
Self-Instructional int num[5], sum;
178 Material float average;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

cout << “Enter the elements of array: “; NOTES


for (int i=0;i<5;i++)
cin>>num[i];
//for printing elements of array
//Also calculate sum and average of array elements
sum=0;
average=0;
cout << “Print the elements of array: “;
for (int i=0;i<5;i++)
{
cout<<endl<<“num[“<<i<<“]: “<<num[i];
sum += num[i];

average = sum/5.0;

cout<<endl<<“Sum of array elements are:”<<sum;


cout<<endl<<“Average of array elements
are:”<<average;

return 0;
}
Output
Enter the elements of array: 4
7
8
2
67
Print the elements of array:
num[0]: 4
num[1]: 7
Self-Instructional
num[2]: 8 Material 179

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES num[3]: 2
num[4]: 67
Sum of array elements are:88
Average of array elements are:17.6
Here num[5] array single dimensional array is declared.
Values are assigned after declaration.

7.4.2 Multi-Dimensional Array

Multi-Dimensional array represents an array that can have any number of dimensions.
The syntax is as follows:
data_type array_name[size1][size2];
size1, size2 represents the number of elements in dimension1 and dimension2.
Example
float matrix [5][5]; // two dimensional array
float matrix[3][4][5]; // three dimensional array

Self-Instructional
180 Material Fig. 7.3 Two Dimensional Array

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

Example 7.6: Write a program to input marks of five students where each student has NOTES
five subjects. Also calculate the average marks for each student.
#include <iostream>

using namespace std;

int main()
{
int marks[5][5], sum[5];
float average[5];
cout << “Enter the marks of students: “;
for (int i=0;i<5;i++)
{
cout << endl<<“Enter the marks of “<< i+1<< “
student: “;
for (int j=0;j<5;j++)
cin>>marks[i][j];
}

cout << “Print the marks of students: “;


for (int i=0;i<5;i++)
{
sum[i]=0;
average
[i]=0;
cout<<endl<<“Marks of “<<i+1<<“student are:
“;
for (int j=0;j<5;j++)
{
cout<<endl<<marks[i][j];
sum[i] += marks[i][j];
}
average[i] = sum[i]/5.0;
cout<<endl<<“Average marks of”<<i+1<< Self-Instructional
Material 181

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES “students is:”<<average[i];


}

return 0;
}
Enter the marks of students:
Enter the marks of 1 student: 78
90
78
99
88
Enter the marks of 2 student: 99
67
56
89
67
Enter the marks of 3 student: 89
90
89
78
90
Enter the marks of 4 student: 78
67
56
89
90

Self-Instructional
Enter the marks of 5 student: 90
182 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

98 NOTES
98
97
94
Print the marks of students:
Marks of 1student are:
78
90
78
99
88
Average marks of1students is:86.6
Marks of 2student are:
99
67
56
89
67
Average marks of2students is:75.6
Marks of 3student are:
89
90
89
78
90
Average marks of3students is:87.2
Marks of 4student are: Self-Instructional
Material 183

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 78
67
56
89
90
Average marks of4students is: 76
Marks of 5student are:
90
98
98
97
94
Average marks of 5students is: 95.4

Explanation

Here two dimensional array was taken marks [5][5].


Average marks of each student is also calculated.

7.5 PASSING ARRAY TO FUNCTION

We can also pass arrays to functions.


The syntax is as follows:
function_name(array_name);
Example 7.7: Write a program to find minimum element of array.
/* Online C++ Compiler and Editor */
#include <iostream>
using namespace std;
Self-Instructional
int min(int num[5]);
184 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

int main() NOTES


{
int num[5], minimum;
cout<<“Enter elements of array”;
for (int i=0;i<5;i++)
{
cin>>num[i];
}

minimum = min(num); // num array is passed to function


min
cout<<endl<<“The minimum element in array is: “<<
minimum;

return 0;
}

//Function to find min. Array is passed as argumnet


int min(int num[5])
{
int minimum;
//cout<<endl<<minimum;

cout<<endl<<“Printing elements in array”;


for (int i=0;i<5;i++)
{
cout<<num[i]<<“ “;
}

minimum = num[0];
for (int i=1;i<5;i++)
{

if (minimum > num[i])


{ Self-Instructional
Material 185

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES minimum = num[i];


}
}

return minimum;
}
Output
Enter elements of array45
12
34
78
90

Printing elements in array45 12 34 78 90


The minimum element in array is: 12
Example 7.8: Write a program to find maximum from array.
#include <iostream>
using namespace std;

int max(int arr[5]);

int main()
{
int num[5], maximum;
cout<<“Enter elements of array”;
for (int i=0;i<5;i++)
{
cin>>num[i];
}

maximum = max(num); // num array is passed to function


Self-Instructional max
186 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

cout<<endl<<“The maximum element in array is: “<< NOTES


maximum;

return 0;
}

int max(int arr[5])


{
int maximum;

cout<<endl<<“Printing elements in array”;


for (int i=0;i<5;i++)
{
cout<<arr[i]<<“ “;
}

maximum = arr[0];
for (int i=1;i<5;i++)
{

if (maximum < arr[i])


{

maximum = arr[i];
}
}

return maximum;
}
Output
Enter elements of array45
90
43 Self-Instructional
Material 187

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 76
23
Printing elements in array45 90 43 76 23
The maximum element in array is: 90

7.6 POINTERS

Pointers are used to store memory addresses of variables in C++. When we define
variables of any data type in C++, they are assigned address in memory. Pointers are
variables that are used to store these addresses.
The syntax is as follows:
int element; // simple int data type variable element
int *pr; // pointer variable pr of int data type. pr
variable can store memory address
Some of the advantages of using pointers are given below:
 With pointers, execution speed of program becomes faster. Pointer variables
directly accesses memory locations, thus making speed faster.
 Pointers save memory space.
 We can declare array using pointers of any data type without specifying the size
of array.

7.7 POINTER- DECLARATION AND INITIALIZATION

Pointers are represented as


int *pr;

data_type *pointer_varaible_name;
Data type can be int, char, float, etc.
Self-Instructional
188 Material *operator tells variable declared is pointer

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

int element=90; // simple int data type variable NOTES


element
int *pr;

pr= &element; //pointer variable pr is assigned address


of variable element.
Example 7.9: Write a program to show functioning of pointer.
#include <iostream>
using namespace std;
int main()
{
int element =90;
int *pr;

pr = &element;
cout<<endl<<“Element is: “<<element;
cout<<endl<<“Adderess of element is: “<<&element;
cout<<endl<<“pr pointer to element contains
address: “ <<pr;
cout <<endl <<“Value of address stored in pr is:
“<<*pr;
}
Output
Element is: 90
Addresses of element is: 0x7ffe2897a05c
pr pointer to element contains address: 0x7ffe2897a05c
Value of address stored in pr is: 90

Note: Different values of address, memory locations may be obtained.


Values at pointer addresses can be accessed using *pr

Self-Instructional
Material 189

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES

Fig. 7.4 Pointer Representation in Memory

Example 7.10: Write program to create and access array elements using pointers.
#include <iostream>
using namespace std;

int main()
{
int *arr, size;

cout<<“Enter the number of elements of array: “;


cin>>size;

arr = new int[size];


cout<<“Enter the elements of array: “;
for (int i=0; i<size;i++)
{
cin>> arr[i];
}

cout<<endl<<“The elements of array are: “;


for (int i=0; i<size;i++)
{
cout<<endl<<“Element at address “<<arr<<“is:
“<<*arr <<“ “;
arr++;
}

Self-Instructional
190 Material
}

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

Enter the number of elements of array: 5 NOTES


Enter the elements of array: 34
12
67
78
45
The elements of array are:
Element at address 0x55b3cf3ef6d0is: 34
Element at address 0x55b3cf3ef6d4is: 12
Element at address 0x55b3cf3ef6d8is: 67
Element at address 0x55b3cf3ef6dcis: 78
Element at address 0x55b3cf3ef6e0is: 45

Explanation

In this program, size of array is not declared initially rather it is delayed till runtime.
This is known as dynamic allocation and achieved using pointers.
nt array of specified size is assigned to pointer variable ptr at run time. Elements
are assigned to array through for loop
ptr is pointing to base addrerss of array, i.e., arr[0]
when arr++ is used, pointer starts pointing to next address that is arr[1] and so
on.
This is how successive array elements are accessed.
cout<<endl<<“Element at address “<<arr<<“is: “<<*arr
<<“ “;
Above line prints first address of element and then element present at that address
Since size of int is 4 bytes, please note addresses represented in hexadecimal
notation are increased by four every time
Please note that the size of note depends on compiler. It may vary depending on
compiler from 2 bytes to 4 bytes. Self-Instructional
Material 191

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
7.8 SOLVED EXERCISE

1. Write a program that will prompt the user for a list of n prices. Compute the
average of the prices and find out all the prices that are higher than the calculated
average.
#include <iostream>
using namespace std;

float average (int *arr, int size);


void check_larger_average(int *arr, int size, float
num);

int main()
{
int *arr, size;
float average_price;
cout<<“Enter the number of elements of array: “;
cin>>size;

arr = new int[size]; //dynamic allocation of


array is done here
cout<<“Enter the prices: “;
for (int i=0; i<size;i++)
{
cin>> arr[i];
}

average_price = average(arr,size); //base address


arr is passed to function along with size
cout<<endl<<“Average of prices are:
“<<average_price;

check_larger_average (arr,size,average_price);
Self-Instructional
192 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

} NOTES

float average (int *arr, int size)


{
float sum =0; float average =0;
cout<<endl<<“The elements of array are: “;
for (int i=0; i<size;i++)
{
cout<<endl<<“Element of array are: “<<arr[i];
sum += arr[i];
}

average = sum/size;

return average;
}
void check_larger_average(int *arr, int size, float
num)
{
cout<<endl<<“Prices larger than average price are:
“;
for (int i=0; i<size;i++)
{
if (num < arr[i])
{
cout <<endl<< arr[i];
}
}
}

Enter the number of elements of array: 5


Enter the prices: 23
67
45 Self-Instructional
Material 193

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 12
90
The elements of array are:
Element of array are: 23
Element of array are: 67
Element of array are: 45
Element of array are: 12
Element of array are: 90
Average of prices are: 47.4
Prices larger than average price are:
67
90
2. Write a program to perform the following operations on an input string
a. Print length of the string
b. Find frequency of a character in the string
c. Print whether characters are in uppercase or lowercase
d. to check whether a given string is palindrome or not
#include <iostream>
#include <cstring>
using namespace std;

void check_palindrome(char arr_str[], int size);


void check_case(char arr_str[], int size);
void check_freq(char arr_str[], int size);

int main()
{
char str[100];
cout<<“Enter the string: “;
Self-Instructional
cin.get(str,100);
194 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

cout<<endl<<“You entered “; NOTES


cout<<str;
cout<<endl<<“length of entered string
is:”<<strlen(str);

check_palindrome(str,strlen(str));

check_case(str,strlen(str));

check_freq(str,strlen(str));
return 0;
}

void check_palindrome(char arr_str[], int size)


{
int flag = 0;
cout<<endl<<“String in function is: “<<arr_str;

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


{
if(arr_str[i] != arr_str[size-i-1])
{
flag = 1;
break;
}
}

if (flag)
{
cout<<endl<<“String is not palindrome”;
}
else
{
cout<<endl<<“String is palindrome”;
} Self-Instructional
Material 195

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES }
void check_case(char arr_str[], int size)
{
cout<<endl<<“String in function check_case is:
“<<arr_str;
for(int i=0;i < size ;i++)
{
if(isupper(arr_str[i]))
{
cout<<endl<<“Char “<<arr_str[i]<<“ is in
Upper case”;
}
else
{
cout<<endl<<“Char “<<arr_str[i]<<“ is in
Lower case”;
}
}
}

void check_freq(char arr_str[], int size)


{
char tocheck_char; int freq=0;
cout<<endl<<“String in function check_freq is:
“<<arr_str;

cout<<endl<<“Enter the character for which you


want to check frequency: “;
cin>>tocheck_char;

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


{
if (arr_str[i] == tocheck_char)
freq++;
}
Self-Instructional
196 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

cout<<endl<<“Frequency of “<<tocheck_char <<“ in NOTES


“<<arr_str<<“ is :”<<freq;
}
Output
Enter the string: Hello I am a Student
You entered Hello I am a Student
length of entered string is:20
String in function is: Hello I am a Student
String is not palindrome
String in function check_case is: Hello I am a Student
Char H is in Upper case
Char e is in Lower case
Char l is in Lower case
Char l is in Lower case
Char o is in Lower case
Char is in Lower case
Char I is in Upper case
Char is in Lower case
Char a is in Lower case
Char m is in Lower case
Char is in Lower case
Char a is in Lower case
Char is in Lower case
Char S is in Upper case
Char t is in Lower case
Char u is in Lower case
Char d is in Lower case
Char e is in Lower case Self-Instructional
Material 197

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Char n is in Lower case


Char t is in Lower case
String in function check_freq is: Hello I am a Student
Enter the character for which you want to check frequency: a
Frequency of a in Hello I am a Student is :2

Exercise

1. Write a program to swap two numbers using pointers.


2. Write a program to print array elements in reverse order.
3. Write a program to check if two arrays are same, that is, they contain same
elements.

In-Text Questions
1. What is an array in C++?
a) A collection of objects with different data types
b) A collection of elements of the same data type, stored in contiguous memory
locations
c) A built-in function to handle multiple values
d) A data structure used for sorting elements
2. How do you access elements of an array in C++?
a) Using the dot (.) operator
b) Using the -> operator
c) By specifying the element’s index in square brackets
d) By using the @ symbol followed by the element number
3. What is the index of the first element in an array?
a) 0
b) 1
c) -1
Self-Instructional
d) It depends on the programmer’s choice.
198 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

4. The size of an array must be known at compile time. True or False? NOTES
a) True b) False
5. How do you declare and initialize an array of integers with elements 1, 2, 3, 4,
and 5?
a) int arr[1, 2, 3, 4, 5];
b) int arr[5] = {1, 2, 3, 4, 5};
c) int arr = {1, 2, 3, 4, 5};
d) int arr[] = {1, 2, 3, 4, 5};
6. Can the size of an array be changed once it is declared?
a) Yes, using the realloc() function. b) Yes, using the resize() function.
c) No, the size is fixed once declared. d) Only if the array is empty.
7. What happens if you try to access an element beyond the array’s size in C++?
a) The program throws an error and terminates.
b) The program continues to execute, but the result is unpredictable.
c) The program automatically resizes the array.
d) The program adds new elements to the array.
8. How do you find the length of an array in C++?
a) Using the size() function
b) Using the length() function
c) By subtracting the index of the first element from the index of the last element
d) There is no direct method to find the length of an array.
9. An array can hold elements of different data types in C++. Is it true or false?
a) True b) False
10. Which of the following do you need to pass in order to pass an array to a
function in C++?
a) The entire array
b) The size of the array and each element individually
c) Only the size of the array
d) Only the elements that need modification
Self-Instructional
Material 199

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
7.9 SUMMARY

Arrays and pointers are fundamental concepts in C++ that play a crucial role in managing
and manipulating data efficiently. Arrays are collections of elements of the same data
type stored in contiguous memory locations. They are declared with a fixed size and
are accessed using zero-based indexing. Pointers, on the other hand, are variables
that store memory addresses. In C++, arrays and pointers are closely related, as an
array’s name can be considered a constant pointer to its first element, enabling
convenient access to array elements using pointer notation. Additionally, pointers are
used for dynamic memory allocation and deallocation, allowing for the creation of
variable-sized data structures. Understanding the relationship between arrays and
pointers is essential for effective memory management and data handling in C++.
Pointer arithmetic is a powerful feature that allows for traversing arrays and
accessing elements efficiently. However, it also requires caution to prevent accessing
memory outside the allocated boundaries. Dynamic memory allocation using pointers
is particularly valuable when creating data structures with varying sizes at runtime.
Arrays of pointers enable the storage of multiple pointers in an array, each pointing to
different data, a common use case when managing arrays of strings. Overall, mastering
arrays and pointers is vital for C++ programmers to work with data structures effectively
and ensure proper memory handling in their applications.

7.10 GLOSSARY

 Array: A collection of elements of the same data type stored in a contiguous


memory block and accessed using an index.
 Pointer: A variable that stores the memory address of another variable or object.
 Dereference: The act of accessing the value located at a memory address
stored in a pointer using the * operator.
 Array Element: A single data item within an array, identified by its position
Self-Instructional
(index) in the array.
200 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Arrays and Pointers in C++

 Pointer Arithmetic: The manipulation of pointers using arithmetic operations, NOTES


like addition and subtraction, to navigate through memory locations or iterate
over arrays.

7.11 ANSWERS TO IN-TEXT QUESTIONS

1. b) A collection of elements of the same data type, stored in contiguous memory


locations
2. c) By specifying the element’s index in square brackets
3. a) 0
4. a) True
5. d) int arr[] = {1, 2, 3, 4, 5};
6. c) No, the size is fixed once declared.
7. d) The program continues to execute, but the result is unpredictable.
8. d) There is no direct method to find the length of an array.
9. b) False
10. a) The entire array

7.12 SELF-ASSESSMENT QUESTIONS

Q1. What is the difference between a class and an object in C++?


Q2. How do you declare and define a class in C++? Can you provide an example?
Q3. Explain the concept of data encapsulation in the context of C++ classes.
Q4. What are constructors and destructors in C++ classes, and why are they
important?
Q5. Describe the principles of inheritance and polymorphism in C++ and how they
relate to classes and objects.
Self-Instructional
Material 201

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
7.13 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


 Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented
programming with C++. Vol. 4. Tata McGraw-Hill, 2008

7.14 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
202 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
UNIT V: CLASSES AND OBJECTS

LESSON 8 CLASSES AND OBJECTS IN C++


Classes and Objects in C++

LESSON 8 NOTES

CLASSES AND OBJECTS IN C++

Dr. Anuradha Singhal


Assistant Professor
Shyama Prasad Mukherjee College
University of Delhi
[email protected]

Structure
8.1 Learning Objectives
8.2 Introduction to Classes
8.3 Classes and Objects
8.4 Advantages of Objects and Classes in C++
8.5 Member Function in Classes
8.5.1 Inside Class
8.5.2 Outside Class
8.6 Constructors in C++
8.7 Destructors in C++
8.8 Objects as Arguments
8.9 Returning Objects from Functions
8.10 Inheritance in C++
8.10.1 Access Modes in Inheritance
8.11 Types of Inheritance
8.11.1 Single Inheritance
8.11.2 Multiple Inheritance
8.11.3 Multilevel Inheritance
8.11.4 Hierarchical Inheritance
8.12 Solved Exercise
8.13 Summary
8.14 Glossary
8.15 Answers to In-Text Questions
8.16 Self–Assessment Questions
8.17 References
8.18 Suggested Readings
Self-Instructional
Material 205

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
8.1 LEARNING OBJECTIVES

 To understand the concept of classes and objects in C++


 To explain the initialization and declaration of classes

8.2 INTRODUCTION TO CLASSES

We have studied about inbuilt data types like integer, float, char and boolean. In this
lesson, we will study about user defined data types Classes. Objects are real world
entity like car, employee, student, and vehicle. These real world entities have some
common properties and some common functions. For example all vehicles have tyres,
engine and their function is to move people or things around. We can say that object,
a real world entity, has some property and functionality. In C++, we term property as
data members whereas functionality as member functions.

8.3 CLASSES AND OBJECTS

Classes act as a blueprint to create real world entities, i.e., objects. They club together
properties and functionality under one roof. Objects are created at run time. An object
is an instance of class. All members of class are accessed through objects.

Self-Instructional
206 Material Fig 8.1 Class Representation in Memory

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

The syntax of class is given below: NOTES


class class_name
{
// class definition
access_specifier: // public, protected,
or private
data_member1; // data members
data_member2; // data members
member_function1(){} // member functions
member_function2(){} // member functions
};
class is reserved keyword
class_name specifies name of real world entity we want to create
access_specifier control the access of the class members within the
class. The specifiers can be public, protected, and private.
data_member are the data elements of the class to store the data values.
member_function are the functions declared inside or outside the class.

Example 8.1: Write a program to illustrate classes.


/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;

class vehicle
{
public: //access specifier is public
int wheels;
string colour;
int mileage; // miles on car

void print()
{ Self-Instructional
Material 207

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES cout<<endl<<“Vehicle has “<< wheels<<“ wheels”;


cout<<endl<<“Vehilce has “ <<colour<<“ colour”;
cout<<endl<<“Vehilce has mileage “<<mileage<<“
mileage”;
}
};

int main()
{
vehicle car_ob;
car_ob.wheels = 4;
car_ob.colour=”Blue”;
car_ob.mileage=20;

cout<<endl<<“Details of car are”;


car_ob.print();

vehicle bike_obj;
bike_obj.wheels = 2;
bike_obj.colour=”Red”;
bike_obj.mileage=15;

cout<<endl<<“Details of bike are”;


bike_obj.print();

return 0;
}
Output
Details of car are
Vehicle has 4 wheels
Vehilce has Blue colour
Vehilce has mileage 20 mileage
Self-Instructional
208 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Details of bike are NOTES


Vehicle has 2 wheels
Vehilce has Red colour
Vehilce has mileage 15 mileage

Explanation

Class vehicle is created.


It has data members: wheels, colour, mileage
It has member function: print

vehicle car_ob;
vehicle bike_obj;
Objects for class vehicle are created: car_obj and bike_obj
This means both car_obj and bike_obj have above data members and
member functions.
Both objects can access their respective data and functions.

bike_obj.wheels = 2;
bike_obj.colour=”Red”;
bike_obj.mileage=15;
Data members of class are accessed
bike_obj.print();
member function of class is accessed
Access Specifier is public which means data members and member functions
are public and can be used anywhere in program
We can also have combination of private, protected, and public access modifiers.

Self-Instructional
Material 209

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES

Fig. 8.2 Representation of Objects in Memory

Private access specifier signifies that the data member or functions are private
to class and can only be accessed within the class. It is also a default access specifier
which means if no access specifier is mentioned, then by default those data members
or member functions are considered private.
Public access specifier signifies data member or functions are public to class
and can be accessed anywhere, inside or outside the class.
Example 8.2: Write a class to show how private and public members of class are
accessed.
/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;

class vehicle
{
private:
int wheels;
string colour;
int mileage; // miles on car

public:
void set(int w, string c, int m)
{
wheels = w;
colour= c;
Self-Instructional
210 Material mileage = m;

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

} NOTES
void display()
{
cout<<endl<<“Vehicle has “<< wheels<<“ wheels”;
cout<<endl<<“Vehilce has “ <<colour<<“ colour”;
cout<<endl<<“Vehilce has mileage “<<mileage<<“
mileage”;
}
};

int main()
{
vehicle car_ob;

// Below statements are invalid


//As wheels, colour and mileage are now private
//They can only be accessed from inside class or
from inside public data functions of class
/*
Invalid block of code
car_ob.wheels = 4;
car_ob.colour=”Blue”;
car_ob.mileage=20;*/
car_ob.set(4,”Brown”,20);
cout<<endl<<“Details of car are”;
car_ob.display();
return 0;
}
Output
Details of car are
Vehicle has 4 wheels
Vehicle has Brown colour
Vehicle has mileage 20 mileage
Self-Instructional
Material 211

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Explanation

Private data members can be accessed only from inside class or from member functions.
private:
int wheels;
string colour;
int mileage;

Above are private data members.

public:
void set(int w, string c, int m){};
void display(){};

Above are public member functions.

8.4 ADVANTAGES OF OBJECTS AND CLASSES


IN C++

Need and implementation of encapsulation, abstraction, inheritance, polymorphism,


etc., are the main characteristics of the class which are discussed in this section. Classes
and objects help to incorporate object-oriented features in C++. Following are some
of characteristics:
 Encapsulation: With classes, data member and member functions are bounded
as single unit. This helps to hide the implementation details and provide a clean
interface for interacting with the data. Encapsulation helps in organizing code
and prevents unauthorized access to data, improving security and maintainability.
In the C++ programming language, encapsulation is achieved through the use of
classes and access modifiers. An illustrative example can be found in the preceding
section for reference purposes. The relevant data members and methods of
vehicle are kept in single unit called vehicle class.
Self-Instructional
212 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

 Modularity: Classes promote modularity by providing a way to divide a large NOTES


program into smaller and self-contained units. Each class can represent a specific
entity or concept, with its own set of attributes (data members) and behaviours
(member functions). This modular approach makes code more manageable,
reusable, and easier to maintain and debug.
 Abstraction: We can define a class to represent a real-world entity or a concept,
and the class’s internal workings are hidden from the outside world. Users of
the class only need to know how to interact with it using its public interface.
Abstraction simplifies the complexity of a system by focusing on essential features
and hiding unnecessary details.
Example 8.3: Write a program to demonstrate the concept of abstraction.
#include <iostream>
using namespace std;

class FindSquare {
private:
// private variables
int input, result;
public:
void square(int x)
{
input = x;
result = input * input;
cout<<“The square of “<<input<<“ is
“<<result<<endl;
}
};
int main()
{
FindSquare sq;
sq.square(5);
/* In valid block of code
cout<<sq.input; */
return 0;
Self-Instructional
} Material 213

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Output
The square of 5 is 25

Explanation

The private members input and result are only accessible to the member function
“square()” of the class and not accessible outside the class. In other words, the details
and working of private members of the class are hidden from the outside world of the
class, and can be accessed through the class members only. The variables input and
result are not accessible even with the object “sq” of the class, since they are declared
private.
 Inheritance: C++ supports inheritance, which allows you to create new classes
based on existing ones. Inheritance enables code reuse and promotes the concept
of “is-a” relationships. By deriving a new class from a base class, we inherit its
attributes and behaviours while adding or modifying them as needed. Inheritance
helps in creating hierarchies of classes and promotes code extensibility and
flexibility.
 Polymorphism: Polymorphism is the ability to treat objects of different classes
in a uniform manner. C++ supports both compile-time polymorphism (function
overloading) and runtime polymorphism (virtual functions). Polymorphism allows
you to write generic code that can work with the objects of different types,
improving code flexibility and reusability. For the implementation of function
overloading, please consult section 6.6.
 Object instances: Objects are instances of classes. They represent specific
entities in your program. By creating multiple objects of the same class, you can
work with different instances of data and behaviour. This enables you to model
and manipulate complex systems more effectively.
These advantages of classes and objects in C++ contribute to writing more
modular, maintainable, and reusable code, enhancing the overall efficiency and structure
of your programs.

Self-Instructional
214 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

NOTES
8.5 MEMBER FUNCTION IN CLASSES

In C++, member functions can be defined inside class or outside class definition. Both
are defined below.

8.5.1 Inside Class

In the previous examples, we have observed member functions being defined inside
class. Let us see one more example when member function is defined inside class
definition.
Example 8.4: Write a program to illustrate when member function is defined inside
class definition.
#include <iostream>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:

void set (int l, int w)


{
length = l;
width=w;
}
int area() {
return length * width;
}

int perimeter() {
return 2 * (length + width); Self-Instructional
} Material 215

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES };

int main ()
{

Rectangle myRectangle;
myRectangle.set(5,4);
cout << endl <<“Area is: “ <<myRectangle.area() ;
cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;

return 0;

}
Output
Area is: 20
Perimeter is: 18

Explanation

Data members are private and can be accessed only inside class or by class member
functions.
Here all member functions are defined inside class definition.

8.5.2 Outside Class

Member functions can also be defined outside class definition. To define member
function outside class definition, scope resolution operator :: is used along with class
name and function name.
Example 8.5: Write a program to illustrate when member function is defined outside
class definition.
#include <iostream>
using namespace std;
Self-Instructional
216 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

class Rectangle { NOTES


private:
int length;
int width;

public:
void set(int l, int b);
int area();
int perimeter();

};

void Rectangle :: set (int l, int w)


{
length = l;
width=w;
}

int Rectangle :: area() {


return length * width;
}

int Rectangle :: perimeter() {


return 2 * (length + width);
}

int main ()
{

Rectangle myRectangle;
myRectangle.set(5,4);
cout << endl <<“Area is: “ <<myRectangle.area() ;
cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;
Self-Instructional
Material 217

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES return 0;
}
Output
Area is: 20
Perimeter is: 18

Explanation

Here, member functions are only declared inside class.


void set(int l, int b);
int area();
int perimeter();
Their definitions are given outside class.
There is no difference in calling of member function whether they are defined
inside or outside class definition.

8.6 CONSTRUCTORS IN C++

In C++, constructors are special member functions that are automatically called when
an object of a class is created. Constructors are responsible for initializing the object’s
data members and preparing them for use. They have the same name as the class and
do not have a return type (not even void).
There are different types of constructors in C++. Some of them are given below:
 Default Constructor: It is a constructor that is automatically generated by the
compiler if no constructor is defined explicitly. It does not take any arguments
and initializes the data members to their default values (e.g., zero for numeric
types, blank for char, etc.).
 Parameterized Constructor: It is a constructor that accepts parameters,
allowing you to initialize the object’s data members with specific values at the
time of creation.
Self-Instructional
218 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

 Copy Constructor: It is a constructor that creates a new object by making a NOTES


copy of an existing object. It is used when an object is initialized with another
object of the same class.
 Overloaded Constructors: Constructors can be overloaded, which means
you can have multiple constructors with the same name but different parameters.
Overloaded constructors allow objects to be initialized in different ways based
on the arguments passed during object creation.
Constructors can be defined both inside and outside class definition.
Example 8.6: Write a program to illustrate default constructors in C++.
/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}
int area();
int perimeter();

};

int Rectangle :: area() {


Self-Instructional
return length * width; Material 219

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES }

int Rectangle :: perimeter() {


return 2 * (length + width);
}

int main ()
{

Rectangle myRectangle;

cout << endl <<“Area is: “ <<myRectangle.area() ;


cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;

return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4

Explanation
Rectangle()
is default constructor with same name as class and no return type.
Here data members are assigned default values.
Rectangle myRectangle;
When myRectangle object is created, since member functions are not
initialized so values in default constructor are assigned to length and width.
Example 8.7: Write a program to illustrate parametrized constructors in C++.
/* Online C++ Compiler and Editor */
#include <iostream>
Self-Instructional
220 Material #include <cstring>

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

using namespace std; NOTES

class Rectangle {
private:
int length;
int width;

public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}

Rectangle(int l, int w);

int area();
int perimeter();

};

Rectangle :: Rectangle (int l, int w)


{
cout<<endl<<“I am in Parametrized constructor”;
length = l;
width = w;
}

int Rectangle :: area() {


return length * width;
}

int Rectangle :: perimeter() {


return 2 * (length + width); Self-Instructional
Material 221

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES }

int main ()
{

Rectangle myRectangle;

cout << endl <<“Area is: “ <<myRectangle.area() ;


cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;

Rectangle myRectangle2(5,6);

cout << endl <<“Area is: “ <<myRectangle2.area()


;
cout<< endl <<“Perimeter is: “
<<myRectangle2.perimeter() ;

return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4
I am in Parametrized constructor
Area is: 30
Perimeter is: 22

Explanation
Rectangle myRectangle;
Here default constructor is called.

Self-Instructional Rectangle myRectangle2(5,6);


222 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Here Parametrized constructor is called. NOTES


There is no difference in calling for both default and parametrized constructors.
Both default and parametrized constructors can be defined inside and outside
class.
Example 8.8: Write a program to illustrate copy constructors in C++.
/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;

class Rectangle {
private:
int length;
int width;

public:
Rectangle()
{
cout<<endl<<“I am in default constructor”;
length = 1;
width = 1;
}

Rectangle(int l, int w);


Rectangle (Rectangle &obj);

int area();
int perimeter();

};

Rectangle :: Rectangle (int l, int w)


{
cout<<endl<<“I am in Parametrized constructor”;
Self-Instructional
length = l; Material 223

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES width = w;
}

Rectangle:: Rectangle(Rectangle &obj) {


cout<<endl<<“I am in Copy constructor”;
length = obj.length;
width = obj.width;
}

int Rectangle :: area() {


return length * width;
}

int Rectangle :: perimeter() {


return 2 * (length + width);
}

int main ()
{

Rectangle myRectangle;

cout << endl <<“Area is: “ <<myRectangle.area() ;


cout<< endl <<“Perimeter is: “
<<myRectangle.perimeter() ;

Rectangle myRectangle2(5,6);
cout << endl <<“Area is: “ <<myRectangle2.area()
;
cout<< endl <<“Perimeter is: “
<<myRectangle2.perimeter() ;

Rectangle myRectangle3 = myRectangle2;

Self-Instructional cout << endl <<“Area is: “ <<myRectangle3.area()


224 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

; NOTES
cout<< endl <<“Perimeter is: “
<<myRectangle3.perimeter() ;
Rectangle myRectangle4(myRectangle2) ;

cout << endl <<“Area is: “ <<myRectangle4.area()


;
cout<< endl <<“Perimeter is: “
<<myRectangle4.perimeter() ;

return 0;
}
Output
I am in default constructor
Area is: 1
Perimeter is: 4
I am in Parametrized constructor
Area is: 30
Perimeter is: 22
I am in Copy constructor
Area is: 30
Perimeter is: 22
I am in Copy constructor
Area is: 30
Perimeter is: 22

Explanation

Copy constructors are used to copy data of one object to another

Rectangle myRectangle3 = myRectangle2;


Rectangle myRectangle4(myRectangle2) ;
Self-Instructional
Both are examples of copy constructor being called. Material 225

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Example 8.9: Write a program to illustrate overloaded constructors in C++.


/* Online C++ Compiler and Editor */
#include <iostream>
#include <cstring>
using namespace std;

class MyClass {
public:
int value;

// Default constructor
MyClass() {
cout<<endl<<“I am in default constructor”;
value = 0;
}

// Parameterized constructor with a single integer


argument
MyClass(int v) {
cout<<endl<<“I am in constructor with one
parameter”;
value = v;
}

// Parameterized constructor with two integer


arguments
MyClass(int v1, int v2) {
cout<<endl<<“I am in constructor with two
parameter”;
value = v1 + v2;
}
};

int main ()
Self-Instructional {
226 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

NOTES
MyClass obj1;
MyClass obj2(5);
MyClass obj3(3, 4);
return 0;
}

Output
I am in default constructor
I am in constructor with one parameter
I am in constructor with two parameter

Explanation
MyClass obj1;
Calls the default constructor, obj1.value = 0

MyClass obj2(5);
Calls the parameterized constructor with one argument, obj2.value = 5
MyClass obj3(3, 4);
Calls the parameterized constructor with two arguments, obj3.value = 7
By providing Overloaded constructors, you can create objects of the MyClass
class in different ways, depending on your needs.

8.7 DESTRUCTORS IN C++

A destructor is a special member function of a class that is automatically called when


an object of that class is destroyed. The destructor is responsible for cleaning up any
resources allocated by the object during its lifetime. It is defined using the tilde (~)
followed by the class name.
Self-Instructional
Material 227

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Example 8.10: Write a program to illustrate destructors in C++.


#include<iostream>
using namespace std;

class MyClass {
public:
// Constructor
MyClass() {
cout<<endl<<“I am in constructor”;
}

// Destructor
~MyClass() {
cout<<endl<<“I am in Destructor”;
}
};

int main()
{
MyClass obj;
return 0;

}
Output
I am in constructor
I am in Destructor

Explanation
MyClass obj;

When obj is created, constructor is called.


When obj is going out of scope, destructor is called.
Self-Instructional
228 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

The destructor is useful for performing cleanup operations such as releasing NOTES
memory, closing file handles, or releasing any other resources acquired by the object.
It ensures that the object leaves a clean state before its memory is deallocated.
Few important points regarding destructors are as follows:
 Destructors do not have parameters and do not return any value.
 A class can have only one destructor, and it cannot be overloaded.
 Destructors are automatically invoked in the reverse order of the object’s
construction within a scope.

8.8 OBJECTS AS ARGUMENTS

We can pass objects as parameters to functions in a similar manner as we pass regular


parameters. As the copy of parameters is created while they are passed to functions,
the copy of objects is also created while they are passed as arguments to functions.
Example 8.11: Write a program to pass class objects as arguments to function.
#include<iostream>
using namespace std;

class Integer {
public:
int x;

// Constructor
Integer() {
cout<<endl<<“I am in constructor”;
x = 0;
}

Integer(int a) {
c o ut <<en dl<<“ I am in p ar am et riz ed
constructor”;
Self-Instructional
x = a; Material 229

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES }

Integer (Integer &obj)


{
cout<<endl<<“I am in copy constructor”;
x = obj.x;
cout<<endl<<“my Value is: “<<obj.x;
}

};

void addition (Integer obj1, Integer obj2)


{
Integer obj3;
obj3.x = obj1. x + obj2.x;
cout<<endl<<“Addition of two Integer Objects is
: “<<obj3.x;
}

int main()
{
Integer obj1(4), obj2(5);
addition(obj1,obj2);
return 0;
}
Output
I am in parametrized constructor
I am in parametrized constructor
I am in copy constructor
my Value is: 5
I am in copy constructor
my Value is: 4
Self-Instructional
230 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

I am in constructor NOTES
Addition of two Integer Objects is : 9

Explanation

Integer class is created. It contains only public data members and member functions
Integer obj1(4), obj2(5);
obj1 and obj2 objects are created. Parametrized constructor is called and
values are initialized.
addition(obj1,obj2);
When addition function is called and obj1 and obj2 are passed as arguments,
copy of both obj1 and obj2 are created and passed to function.
In addition function, Integer obj3;
is created and default constructor is called.
Addition of two Integer objects is performed.

8.9 RETURNING OBJECTS FROM FUNCTIONS

Objects can also be returned from functions.


Example 8.12: Write a program to pass class objects as arguments to function and
return objects from function.
#include<iostream>
using namespace std;
class Integer {
public:
int x;
// Constructor
Integer() {
cout<<endl<<“I am in constructor”;
x = 0;
}
Self-Instructional
Material 231

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Integer(int a) {
c o ut <<en dl<<“ I am in p ar am et riz ed
constructor”;
x = a;
}

Integer (Integer &obj)


{
cout<<endl<<“I am in copy constructor”;
x = obj.x;
cout<<endl<<“my Value is: “<<obj.x;
}

Integer subtraction (Integer obj)


{
Integer temp;
temp.x = x - obj.x;
return temp;
}
};
int main()
{
Integer obj1(4), obj2(5);
Integer obj3 = obj2.subtraction(obj1);
cout<<endl<<“Result of Subtraction “<<obj3.x;
return 0;
}
Output
I am in parametrized constructor
I am in parametrized constructor
I am in copy constructor
my Value is: 4
Self-Instructional
I am in constructor
232 Material
Result of Subtraction 1

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Explanation NOTES
Integer obj1(4), obj2(5);
obj1 and obj2 objects are created and parametrized constructor is called.

Integer obj3 = obj2.subtraction(obj1);


obj2 object called subtraction method and obj1 is passed as argument,
which implies only copy of obj1 is created.

In subtraction method
temp.x = x - obj.x;
current object is obj2
Passed object is obj1
So obj2.x-obj1.x is performed.

Integer object is returned from method and stored to obj3 object.

8.10 INHERITANCE IN C++

Inheritance is a fundamental feature of Object-Oriented Programming (OOP) that


allows us to define a new class (called the derived class) based on an existing class
(called the base class or parent class). The derived class inherits the data members
and member functions of the base class, and it can also add its own unique data
members and member functions.
To create a derived class, we use the colon (:) followed by the access specifier
public, protected, or private, and then the name of the base class. The access specifier
(public, protected, or private) determines the visibility of the inherited members in the
derived class.

Self-Instructional
Material 233

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Basic prototype


class className: access Specifier base_class_name
Pseudo Example
// Base class
class Shape {
public:
void draw() {
// Draw the shape
}
};

// Derived class
class Circle : public Shape // Circle class Inherits
Shape Class
{
public:
void calculateArea() {
// Calculate the area of the circle
}
};

Explanation

In above example, the Shape class is the base class, and the Circle class is the derived
class. The Circle class publicly inherits from Shape using the public access specifier.
This means that the draw() function from the Shape class is accessible in the Circle
class.
We can create objects of the derived class and use both the inherited members
and the new members defined in the derived class.
Inheritance allows us to create a hierarchy of classes, where derived classes
can further inherit from other base classes. This helps in achieving code reuse, extensibility,
and provides a way to model real-world relationships between objects.

Self-Instructional
234 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Example 8.13: Write a program to illustrate inheritance. NOTES


#include<iostream>
using namespace std;

// Base class
class Shape {
public:
void draw() {
cout<<endl<<“Hi i am in Shape Base class Draw”;
}
};

// Derived class
class Circle : public Shape {
public:
void calculateArea() {
cout<<endl<<“Hi i am in circle Derived class
calculateArea”;
}
};

int main() {
Circle circle;
circle.draw(); // Accesses the
inherited draw() function
circle.calculateArea(); // Accesses the new
calculateArea() function

return 0;
}
Output
Hi i am in Shape Base class Draw
Hi i am in circle Derived class calculateArea
Self-Instructional
Material 235

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Explanation
class Circle : public Shape
Circle class publicly inherits Shape class.
It can access draw function.
In this example, we can call the draw() function from the base class through
the circle object of the derived class. Additionally, we can call the
calculateArea() function, which is specific to the Circle class.
Inheritance is used to represent is-a relationship. For example
 Dog is a mammal.
 Circle is a shape.

8.10.1 Access Modes in Inheritance

In C++, classes can be inherited using three access modes, i.e., Public, Private and
Protected.
These access modes are described below:
 public: If base class is inherited in public mode, then the data members and
member functions of the base class are inherited by the derived class just as
they are.
 private: If base class is inherited in private mode, then the data members and
member functions of the base class, become private members in the derived
class.
 protected: If base class is inherited in protected mode, then the public members
of the base class become protected members in the derived class.
To Note: The private members of the base class are always private in the derived
class.
How access specifier of data members and member functions of base class
changes in derived class when inherited by derived class in public, private and protected
mode is depicted below.

Self-Instructional
236 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Data member or Inheritance Access Specifier NOTES


member function of Public Protected Private
base class
Public Public Protected Private
Protected Protected Protected Private
Private Private Private Private

8.11 TYPES OF INHERITANCE

Some types of Inheritance in C++ are discussed below.

8.11.1 Single Inheritance

In single heritance, derived class has only one base class.

Fig 8.3 Single Level Inheritance

Example 8.14: Write a program to implement single level inheritance in C++.


#include <iostream>
using namespace std;

class Shape{
int var1;
int var2;

public:
void area (int var1, int var2); Self-Instructional
}; Material 237

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
void Shape:: area (int var1, int var2)
{

cout<<endl<<“Hi i am in Shape area: “<<var1<<“


“<<var2;

class Rectangle: public Shape {


private:
int len;
int breadth;
public:
void area (int l, int b);

};

void Rectangle:: area (int l, int b)


{

cout<<endl<<“Hi i am in Rectangle area: “<<l * b;

int main() {

Rectangle obj1;
obj1.area(4,5);

Self-Instructional
238 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Output NOTES
Hi i am in Rectangle area: 20
Explanation
class Rectangle: public Shape

class Rectangle has publically inherited Shape class

Please note that here both classes Rectangle and Shape have function area
with void return type and two int parameters.
This concept where function in derived class has same signature as that of function
in base class is known as overriding function.

Rectangle obj1;
obj1.area(4,5);
When obj1 is created, obj1 of derived class is called and that of base class
is overridden.
Example 8.15: Write a program to show single inheritance when base class is inherited
using private access modifier by derived class.
#include <iostream>
using namespace std;

class Base{
private:
int var;
public:
void print (int v);
};

void Base:: print (int v)


{

cout<<endl<<“Hi i am in Base: “<<v;

Self-Instructional
} Material 239

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
class Derived: private Base {
private:
int xyz;
public:
void displayall (int abc, int pqr);

};

void Derived:: displayall (int l, int b)


{

cout<<endl<<“Hi i am in Derived : “ <<l;


print(b);

int main() {

Derived obj1;

obj1.displayall(4,5);

// obj1.print(9); Invalid code

}
Output
Hi i am in Derived : 4
Hi i am in Base: 5

Explanation

Since base class is inherited using private, so its data members and member functions
cannot be accessed outside body of class definition.
Self-Instructional
240 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

8.11.2 Multiple Inheritance NOTES

When derived class has more than one base class, then it is multiple inheritance. It is
also depicted in Figure 8.4.

Fig 8.4 Multiple Inheritance

Example 8.16: Write a program to implement multiple inheritance in C++.


#include <iostream>
using namespace std;

class Base1{
public:
Base1()
{
cout<<endl<<“Hi i am in Base 1”;
}

};

class Base2{
public:
Base2()
{
cout<<endl<<“Hi i am in Base 2”;
}
};

class Derived: public Base1, public Base2 {


public: Self-Instructional
Material 241
Derived()

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES {
cout<<endl<<“Hi i am in Derived”;
}

};

int main() {

Derived obj1;
}
Output
Hi i am in Base 1
Hi i am in Base 2
Hi i am in Derived

Explanation

When we create object of Derived class, constructors of both base classes and derived
classes are called. Constructors of base class are called in order of inheritance. Here
Base class 1 is inherited first, so its constructor is called first.

8.11.3 Multilevel Inheritance

Self-Instructional
242 Material Fig 8.5 Multilevel Inheritance

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Example 8.17: Write a program to show multilevel inheritance. NOTES


#include <iostream>
using namespace std;

class Base{
public:
Base()
{
cout<<endl<<“Hi i am in Base “;
}

};

class Derived: public Base{


public:
Derived()
{
cout<<endl<<“Hi i am in Derived”;
}

};

class Derived2: public Derived{


public:
Derived2()
{
cout<<endl<<“Hi i am in Derived2”;
}

};

int main() {

Derived2 obj1;
Self-Instructional
} Material 243

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Output
Hi i am in Base
Hi i am in Derived
Hi i am in Derived2
When Derived2 object is created, constructors are called in order objects are
instantiated.
First Base class constructor is called, then Derived class constructor is called
and lastly Derived2 class constructor is called.

8.11.4 Hierarchical Inheritance

When we have more than one derived class, inheriting from same base class then it is
known as hierarchical inheritance.

Fig 8.6 Hierarchical Inheritance

Example 8.18: Write a program to illustrate hierarchical inheritance in C++.


#include <iostream>
using namespace std;

class Base{
public:
Base()
{
cout<<endl<<“Hi i am in Base “;
}

};
Self-Instructional
244 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

class Derived1: public Base{ NOTES


public:
Derived1()
{
cout<<endl<<“Hi i am in Derived1”;
}

};

class Derived2: public Base{


public:
Derived2()
{
cout<<endl<<“Hi i am in Derived2”;
}

};

int main() {
Derived1 obj1;
Derived2 obj2;

}
Output
Hi i am in Base
Hi i am in Derived1
Hi i am in Base
Hi i am in Derived2

Explanation

Both Derived1 and Derived classes inherit from Base class. When their objects are
created, in both cases first base class constructor is called and then derived class Self-Instructional
Material 245
constructor is called.

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
8.12 SOLVED EXERCISE

1. Design a class named Vehicle, having registration number and year as its private
members. Define a suitable constructor and a method to print the details of a
vehicle. Write a C++ program to test the above class.
#include<iostream>
using namespace std;

class Vehicle
{
private:
int registration_number;
int year;
public:
Vehicle()
{
cout<<endl<<“I am in default constructor”;
registration_number = 1234;
year = 2000;
}

Vehicle(int r, int y)
{
cout<<endl<<“I am in parametrized constructor”;
registration_number = r;
year = y;
}

void print();
};

void Vehicle:: print()


Self-Instructional
{
246 Material cout<<endl<<“Registration Number is:

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

“<<registration_number; NOTES
cout<<endl<<“year is: “<<year;
}

int main()
{
Vehicle obj1;
obj1.print();

Vehicle obj2(3456, 2023);


obj2.print();
return 0;
}
Output
I am in default constructor
Registration Number is: 1234
year is: 2000
I am in parametrized constructor
Registration Number is: 3456
year is: 2023
2. Inherit a class Car from the Vehicle class defined above. Add model to the Car
class. Define a suitable constructor and a method to print the details of a car.
Write a C++ program to test inheritance of this class.
#include<iostream>
#include<cstring>
using namespace std;

class Vehicle
{
private:
int registration_number;
int year;
Self-Instructional
public: Material 247

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Vehicle()
{
cout<<endl<<“I am in default constructor
Vehicle”;
registration_number = 1234;
year = 2000;
}

Vehicle(int r, int y)
{
cout<<endl<<“I am in parametrized constructor
Vehicle”;
registration_number = r;
year = y;
}

void print();
};

class Car : public Vehicle{


private:
string model;
public:
Car()
{
cout<<endl<<“I am in default constructor car”;
model=”SUV”;
Vehicle();
}

Car(int r, int y, string m)


{
cout<<endl<<“I am in parametrized constructor
Car”;
Self-Instructional model =m;
248 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

Vehicle(r,y); NOTES
}
void print();

};
void Vehicle:: print()
{
cout<<endl<<“Registration Number is:
“<<registration_number;
cout<<endl<<“year is: “<<year;
}

void Car:: print()


{
Vehicle::print();
cout<<endl<<“Model is: “<<model;
}

int main()
{
Car obj1;
obj1.print();

Car obj2(3456, 2023,”Tata”);


obj2.print();
return 0;
}
Output
I am in default constructor Vehicle
I am in default constructor car
I am in default constructor Vehicle
Registration Number is: 1234
year is: 2000 Self-Instructional
Material 249

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES Model is: SUV


I am in default constructor Vehicle
I am in parametrized constructor Car
I am in parametrized constructor Vehicle
Registration Number is: 1234
year is: 2000
Model is: Tata

Explanation
Car obj1;
obj1.print();
With this line, when obj1 is created, first default constructor of base class that is
vehicle class is called then constructor of derived class car is called. Also in derived
class, Vehicle constructor is called, so “I am in default constructor Vehicle” is printed
again

obj1.print();
Car class overrides print function of vehicle base class. So it will be called.
Now since we cannot have access to registration number and year as they are private
to vehicle class, so we call base class print by using scope resolution operator ::
Vehicle::print();

Car obj2(3456, 2023,”Tata”);


obj2.print();
Same happens with parametrized constructor

Exercise

1. Create base class fruit with number of calories as data member. And print function
as member function. Make another derived class Mangoes from fruit class.
Add vitamin and colour as data member. Also override print function.
Self-Instructional
250 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

2. Create base class account with money and interest rate as data member. And NOTES
print function as member function. Make another derived class current_account
and savings_account. Add appropriately other data member. Also override print
function.

In-Text Questions
1. What is a class in C++?
a) A collection of functions that perform specific tasks.
b) A user-defined data type that represents a blueprint for creating objects.
c) A built-in data structure for storing multiple values of the same type.
d) A function that is used to initialize objects.
2. How do you define a class in C++?
a) class MyClass { } b) class { }
c) define class MyClass: d) define MyClass:
3. Which access specifier is used when you want to make class members
accessible from outside the class?
a) public b) private
c) protected d) friend
4. What is the default access specifier in a class in C++ if none is specified?
a) public b) private
c) protected d) friend
5. What is the keyword used to create an instance of a class (object) in C++?
a) create b) instance
c) new d) object
6. Can a class contain both member functions and member variables?
a) Yes, but it is not recommended.
b) No, a class can only have member functions or member variables.
c) Yes, a class can have both member functions and member variables.
d) It depends on the access specifier used.
Self-Instructional
Material 251

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES 7. What is a constructor in C++?


a) A member function that is automatically called when an object is created.
b) A member function used to destroy objects.
c) A function used to overload operators in a class.
d) A function that is used to initialize arrays.
8. How is the constructor different from other member functions?
a) Constructors cannot have arguments.
b) Constructors do not have return types.
c) Constructors can only be called explicitly from other member functions.
d) Constructors cannot be overloaded.
9. What is the keyword used to refer to the current object inside a member
function?
a) self b) this
c) me d) current
10. What is the purpose of the destructor in C++?
a) To deallocate memory dynamically allocated for objects.
b) To release resources used by the class.
c) To initialize objects of a class.
d) To perform arithmetic operations.

8.13 SUMMARY

Classes and objects are fundamental concepts in C++ that facilitate the organization
and implementation of object-oriented programming (OOP) principles. In C++, a
class is a blueprint or template that defines a structure for creating objects. It
encapsulates data members (attributes) and member functions (methods) that define
the behavior of the objects created from the class. These objects are instances of the
class, and they can have their own unique data while sharing the same set of behaviors
Self-Instructional
defined in the class. Classes provide a way to model real-world entities and their
252 Material

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

interactions, enhancing code modularity and reusability. Object-oriented programming NOTES


promotes concepts like encapsulation, inheritance, and polymorphism, which contribute
to more organized and maintainable code.
C++ supports object-oriented programming through classes, allowing for the
creation of complex software systems with structured data and functionality. In C++,
classes also enable access control mechanisms, like private and public access specifiers,
to restrict or allow access to class members. Constructors and destructors are special
member functions within a class that allow for object initialization and cleanup,
respectively. Inheritance and polymorphism, essential OOP concepts, are also
supported, allowing for code reuse and the implementation of dynamic behavior. Overall,
classes and objects in C++ offer a powerful way to design and implement complex
software systems with a focus on modularity, reusability, and the modeling of real-
world entities and their interactions.

8.14 GLOSSARY

 Class: A blueprint or template for creating objects. It defines the structure and
behavior of objects, including data members and member functions.
 Object: An instance of a class, representing a real-world entity or concept.
Objects encapsulate data and methods defined in the class.
 Instance Variable: A data member (or attribute) of a class that holds the state
or characteristics of an object, with each object having its own set of instance
variables.
 Member Function: A function defined within a class, used to perform actions
and operations on the class’s data members and provide behavior to objects.
 Encapsulation: The concept of bundling data and the methods that operate on
that data within a class, while controlling access to the data through access
specifiers like private, protected, and public.
 Inheritance: A mechanism in C++ that allows a new class (derived class) to
inherit properties and behaviors from an existing class (base class), facilitating
code reuse and hierarchy in object-oriented programming. Self-Instructional
Material 253

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Introduction to Programming Using C++

NOTES
8.15 ANSWERS TO IN-TEXT QUESTIONS

1. b) A user-defined data type that represents a blueprint for creating objects.


2. a) class MyClass { }
3. a) public
4. b) private
5. c) new
6. c) Yes, a class can have both member functions and member variables.
7. a) A member function that is automatically called when an object is created.
8. b) Constructors do not have return types.
9. b) this
10. b) To release resources used by the class.

8.16 SELF–ASSESSMENT QUESTIONS

Q1. What is the difference between a class and an object in C++?


Q2. How do you declare and define a class in C++? Can you provide an example?
Q3. Explain the concept of data encapsulation in the context of C++ classes.
Q4. What are constructors and destructors in C++ classes, and why are they
important?
Q5. Describe the principles of inheritance and polymorphism in C++ and how they
relate to classes and objects.

8.17 REFERENCES

 Schildt, Herbert. Teach yourself C++. McGraw-Hill, Inc., 1992


Self-Instructional  Balagurusamy, E., E. Balagurusamy, and E. Balagurusamy. Object oriented
254 Material programming with C++. Vol. 4. Tata McGraw-Hill, 2008

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
Classes and Objects in C++

NOTES
8.18 SUGGESTED READINGS

 Lafore, Robert. Object-Oriented Programming in C++. Pearson Education,


1997.
 Stroustrup, Bjarne. The C++ Programming Language. Pearson Education, 2013.
 Meyers, Scott. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Addison-Wesley Professional, 2005.
 Josuttis, Nicolai M. The C++ Standard Library: A Tutorial and Reference.
Addison-Wesley Professional, 2012.

Self-Instructional
Material 255

© Department of Distance & Continuing Education, Campus of Open Learning,


School of Open Learning, University of Delhi
INTRODUCTION TO
PROGRAMMING
USING C++

INTRODUCTION TO PROGRAMMING USING C++


B.A. (PROGRAMME) IN COMPUTER SCIENCE DISCIPLINE
PAPER-II DISCIPLINE-A1/ PAPER-III DISCIPLINE-B1
SEMESTER-I
(MINOR PAPER-II)

DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION DEPARTMENT OF DISTANCE AND CONTINUING EDUCATION
UNIVERSITY OF DELHI UNIVERSITY OF DELHI

You might also like