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

Object - Oriented Programming  Using C++.

The document outlines the curriculum for a BCA Semester 2 course on Object-Oriented Programming using C++, focusing on the evolution of programming methodologies, the introduction to OOP, and its fundamental features. Key concepts include encapsulation, inheritance, and polymorphism, which enhance software development by organizing data and functions into manageable objects. The document also emphasizes the importance of understanding procedural programming as a foundation for mastering OOP principles.

Uploaded by

sethinupoor931
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)
6 views

Object - Oriented Programming  Using C++.

The document outlines the curriculum for a BCA Semester 2 course on Object-Oriented Programming using C++, focusing on the evolution of programming methodologies, the introduction to OOP, and its fundamental features. Key concepts include encapsulation, inheritance, and polymorphism, which enhance software development by organizing data and functions into manageable objects. The document also emphasizes the importance of understanding procedural programming as a foundation for mastering OOP principles.

Uploaded by

sethinupoor931
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/ 184

BCA SEMESTER 2

❇ Click the link below to join


the BCA Batch-8 Main Community:
(https://chat.whatsapp.com/
DgVLGa24pLNJpc2Awnmzul)

DCA1210
OBJECT - ORIENTED PROGRAMMING
USING
Unit: 1 - Introduction to Object-Oriented ProgrammingC++ 1
DCA1210: Object-Oriented Programming using C++

❇ Click the link below to join the BCA


Batch-8 Main Community:
(https://chat.whatsapp.com/
DgVLGa24pLNJpc2Awnmzul)

Unit – 1
Introduction to Object-Oriented
Programming

Unit: 1 - Introduction to Object-Oriented Programming 2


DCA1210: Object-Oriented Programming using C++

TABLE OF CONTENTS

Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4
1.1 Objectives - -
2 Evolution of Programming Methodologies - - 5-6
3 Introduction to OOP and its basic features 1, 2, 3, 4, 5, 6 -

3.1 Characteristics of OOP - - 7 - 16

3.2 Benefits of Object-Oriented Programming (OOP) - -


4 Difference between C and C++ - - 17
5 Applications of Object-Oriented Programming (OOP) - - 18
6 Summary - - 19
7 Self-Assessment Questions - 1 20 - 21
8 Glossary - - 22 - 23
9 Sample Programs - - 24 - 28
10 Terminal Questions - - 29
11 Answers - - 30
12 References - - 31

Unit: 1 - Introduction to Object-Oriented Programming 3


DCA1210: Object-Oriented Programming using C++

1. INTRODUCTION
In this unit, learners will learn about the programming that has evolved over time to handle the
growing complexity of software development. Initially, procedural programming was the main
approach, where tasks were broken down into a series of functions. However, as software projects
became bigger and more complex, this method showed its limits, making it harder to maintain and
expand programs. This led to the creation of Object-Oriented Programming (OOP), which organizes
software around "objects"—small units that combine data and the actions that work on that data.

Leraners will also learn important concepts like encapsulation, inheritance, and polymorphism.
Encapsulation protects an object's data from being changed accidentally by other parts of the
program. Inheritance allows new classes to be built on top of existing ones, making it easier to reuse
code. Polymorphism allows the same function to behave differently depending on the object it is used
on. These features make OOP especially useful for developing large and complex software systems.

To effectively learn the topics in this unit, learners should start by mastering the basics of procedural
programming, using hands-on practice and real-world analogies to grasp OOP concepts. Visualizing
relationships between classes and objects, comparing C and C++ through coding exercises, and
exploring real-world applications will reinforce their understanding.

1.1. Objectives
After studying this unit, you should be able to:
• Identify the key programming methodologies that
have evolved over time, including procedural
programming and object-oriented programming.
• Define the basic concepts of Object-Oriented
Programming (OOP).
• List the key characteristics of OOP.
• List the primary differences between C and C++ in
terms of programming paradigms, syntax, and
features.

Unit: 1 - Introduction to Object-Oriented Programming 4


DCA1210: Object-Oriented Programming using C++

2. EVOLUTION OF PROGRAMMING METHODOLOGIES


Computer performs a variety of tasks with the help of programming languages. The first version of a
programming language was the machine-level language. During the1940s, the machine-level
language, which used the binary codes of 0s and 1s to represent computer instructions, was
developed. Machine-level language is also known as low-level programing language. Writing
programs in machine language is symbolic, and had to be error prone (which is impractical). So,
assembly languages were developed in the early 1950s. Assembly languages use mnemonics to write
the instruction of a program.

First high level programming language known as FORTRAN was developed in the year 1957. During
the 1960s, many high level languages were developed to support the needs of various disciplines like
science and engineering, and business. The period between 1970 and 1980 was actually the golden
era for the development of high-level programming languages. During 1970, a procedural
programming language named PASCAL was developed. The C programming language was developed
by Dennis Ritchie at the Bell Labs during the year 1973. In 1980, Bjarne Stroustrup, from the Bell labs,
began the development of the C++ language.

The idea of object-oriented programming gained momentum in the 1970s and in the early 1980s.
Bjorn Stroustrup integrated the object-oriented programming into the C language. C++ is a superset
of C. Several features are similar in C and C++. At this time, many new features like object,
class,inheritance, virtual functions and function overloading were added. Therefore, there is a ‘++’
symbol in C++. The ++ operator in the C++ means many new features were added around this time.
The most notable features are - object, class, inheritance, virtual functions and function overloading.

Limitations of procedural languages:


Procedural languages focused on organizing program statements into procedures or functions. Larger
programs were either broken into functions or modules which had defined purpose and interface to
other functions.

Procedural approach for programming had several problems as the size of the software grew larger
and larger. One of the main problems was that of the data being completely forgotten. The emphasis
was on the action and the data was only used in the entire process. Data in the program was created
by variables, and if more than one function had to access data, then global variables were used. The
concept of global variables itself is a problem as it may be accidentally modified by an undesired

Unit: 1 - Introduction to Object-Oriented Programming 5


DCA1210: Object-Oriented Programming using C++

function. This also leads to difficulty in debugging and modifying the program when several functions
access a particular data.

The object Oriented approach overcomes this problem by modeling data and functions together,
thereby allowing only certain functions to access the required data.

The procedural languages had limitations of extensibility as there was limited support for creating
user-defined data types and defining how these datatypes are to be handled. For example, it would
be difficult if the programmer had to define his own version of string, and define how this new
datatypes will be manipulated. The Object Oriented Programming provides this flexibility through the
concept of class.

Another limitation of the procedural languages is that the program model is not closer to real world
objects. For example, if you want to develop a gaming application of car race, what data you would
use and what functions you would require are difficult questions to answer in the procedural
approach. The object oriented approach solves this further by conceptualizing the problem as group
of objects which have their own specific data and functionality. In the car game, for example we would
create several objects such as player, car, and traffic signal and so on.

Some of the languages that use object oriented programming approach are C++, Java, Csharp,
Smalltalk etc. We will be learning C++ in this Self Learning Material (SLM) to understand the object
oriented programming.

Unit: 1 - Introduction to Object-Oriented Programming 6


DCA1210: Object-Oriented Programming using C++

3. INTRODUCTION TO OOP AND ITS BASIC FEATURES


OOP allows developers to decompose complex problems into smaller, more manageable entities
called objects. Each object encapsulates both data and the functions that operate on that data, creating
a self-contained unit. This decomposition makes the program more organized, as each object
represents a specific aspect of the problem and can be developed and tested independently. Also, this
approach promotes code reuse, as objects can be reused across different parts of the program or even
in different programs.

OOP introduces a controlled interaction between objects, where an object's data can only be accessed
by the functions within that object, preserving the integrity of the data. The design of OOP allows
objects to interact with each other, where the functions of one object can call the functions of another,
enabling collaboration between different parts of the program. This balance between encapsulation
and inter-object communication is a cornerstone of OOP, making it a powerful paradigm for building
complex, scalable, and maintainable software systems.

Figure 1: OOP's data and function organisation

There are several fundamental concepts that are extensively used in object-oriented programming:
• Objects
• Classes
• Data Abstraction and Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing

Unit: 1 - Introduction to Object-Oriented Programming 7


DCA1210: Object-Oriented Programming using C++

Objects: Objects are described as the fundamental run-time entities in an object-oriented system,
representing various elements such as a person, place, bank account, or any other item that the
program needs to manage. They can also represent more abstract data types like vectors, time, and
lists. The objects are chosen based on their relevance to real-world entities, ensuring that they closely
mirror the actual items or concepts they are designed to represent.

Each object occupies memory space and has an associated address, similar to records in Pascal or
structures in C. This emphasizes the tangible nature of objects in memory. The interaction between
objects is also highlighted, where objects communicate by sending messages to each other.

For example, in a program with "customer" and "account" objects, the customer object might send a
message to the account object to request the bank balance. This interaction allows objects to work
together without needing to know the internal details of each other’s data or code, focusing instead
on the type of message accepted and the response returned by the objects.

Figure 2: Representation of an object in two different ways

The figure 2 represents two common notations for representing objects, specifically using the
example of a "STUDENT" object. The first notation lists the object’s data (such as Name, Date-of-birth,
and Marks) and functions (such as Total, Average, and Display) in a structured format, showing how
the object encapsulates both data and behavior. The second notation simplifies the representation by
focusing on the functions associated with the object, emphasizing the different ways objects can be
visualized in object-oriented analysis and design.

Classes: A class is essentially a blueprint for creating objects. Once a class is defined, any number of
objects can be created based on that class. These objects will share the same structure and behaviour
as defined in the class, i.e., they will contain the same type of data and the same functions to
manipulate that data (Hence class can be defined as a collection of similar objects). Objects are
variables of the type class i.e., an object is an instance of a class, and it carries the characteristics (data

Unit: 1 - Introduction to Object-Oriented Programming 8


DCA1210: Object-Oriented Programming using C++

and behavior) defined by the class. For example, if there is a class named "fruit," then objects like
"mango," "apple," and "orange" can be created as instances of the "fruit" class.

A class is described as a collection of objects of a similar type i.e., all objects created from a class share
common attributes and functions.

For example, the class "fruit" may have attributes like color and taste, and functions like ripen or spoil,
which all instances (such as mango, apple, orange) will have.

Classes are considered user-defined data types, which behave similarly to built-in types in a
programming language i.e., just as you can create an integer or a float in C, you can create an object
using the same kind of syntax once the class is defined.

For example, the statement fruit mango; creates an object "mango" that belongs to the class "fruit."

If a class named "fruit" has been defined, then writing fruit mango; in a program will create an object
named "mango," which is an instance of the class "fruit." This object will possess all the characteristics
and behaviors defined in the "fruit" class.

Data Abstraction and Encapsulation: Encapsulation is the process of bundling data and functions
that operate on that data into a single unit, known as a class. This technique ensures that the data
within a class is not accessible directly from the outside world; instead, it can only be accessed or
modified through the functions provided within the class. These functions serve as an interface
between the object's data and the rest of the program. The purpose of encapsulation is to protect the
data from unintended interference or misuse, a principle often referred to as data hiding or
information hiding as shown in figure 3.

Figure 3: Encapsulation

In OOP, classes uses abstraction by defining objects through a list of abstract attributes (like size,
weight, or cost) and corresponding functions that operate on these attributes.

Unit: 1 - Introduction to Object-Oriented Programming 9


DCA1210: Object-Oriented Programming using C++

Data abstraction is a principle in Object-Oriented Programming (OOP) that involves representing


the essential features of an object while hiding the underlying implementation details. It allows
programmers to focus on what an object does rather than how it does it.

By using data abstraction, you can define an interface that exposes only the necessary attributes and
methods needed to interact with an object, while the complexity of how these attributes and methods
are implemented is kept hidden from the user.

Data abstraction is achieved through the use of classes, which encapsulate data (attributes) and
functions (methods) into a single unit. The internal workings of these functions are not visible to the
outside world; instead, the user interacts with the object through a simplified interface that abstracts
away the complexities.

For example, consider a "Car" class in a program. The user of this class might interact with it using
methods like startEngine(), drive(), and stopEngine(). The user does not need to know the intricate
details of how the engine is started or how the car moves—those details are abstracted away. The
focus is on what the car can do (its behavior), not how it does it.

Data abstraction helps in managing complexity, improving code readability, and providing a clear
separation between an object's external interface and its internal implementation.

By focusing on these abstract properties, abstraction allows for the creation of simplified
representations of complex systems. The attributes are often referred to as data members because
they store information, while the functions that manipulate these data members are called methods
or member functions.

Since classes in OOP utilize data abstraction, they are often referred to as Abstract Data Types (ADT).
This term emphasizes that classes provide a high-level interface to the data and behaviors they
encapsulate, abstracting away the details of their implementation. This combination of abstraction
and encapsulation is a key aspect of OOP, enabling the creation of flexible, reusable, and maintainable
code.

Inheritance : Inheritance is one of the fundamental principles of Object-Oriented Programming


(OOP). It allows a new class, known as a derived class or subclass, to inherit properties and
behaviors (attributes and methods) from an existing class, known as a base class or superclass (i.e.,
the process by which a class (or object) can acquire properties and behaviors from another class).
This mechanism enables the creation of a class hierarchy where more specialized classes build on the
general characteristics of more generic ones.

Unit: 1 - Introduction to Object-Oriented Programming 10


DCA1210: Object-Oriented Programming using C++

Figure 4: Inheritence of a property.

For example in figure 4, the "Bird" class represents a general category with common attributes such
as "Feathers" and "Lay eggs." This class is then divided into two subclasses: "Flying Bird" and
"Nonflying Bird," each representing a more specific category. The "Flying Bird" subclass might include
birds like "Robin" and "Swallow," while the "Nonflying Bird" subclass might include "Penguin" and
"Kiwi." These specific bird classes inherit the general characteristics of the "Bird" class and also share
attributes with their immediate parent class, whether it's "Flying Bird" or "Nonflying Bird."

Inheritance promotes code reuse. Instead of writing the same code multiple times, you can define
common functionality in a base class and let derived classes inherit that functionality. This reduces
redundancy and makes code easier to maintain.

Through inheritance, OOP supports polymorphism, where a single function or method can work with
objects of different classes. For example, if a base class Shape has a method draw(), all subclasses like
Circle, Square, and Triangle can override this method to provide their specific implementations. Yet,
all these subclasses can be treated as instances of Shape, allowing for flexible and dynamic method
invocation.

Inheritance makes it easy to extend existing code. You can create new classes based on existing ones
and add or override specific functionalities. This allows developers to build complex systems that can
be easily expanded and adapted without modifying existing code, ensuring that the system remains
stable and maintainable.

Unit: 1 - Introduction to Object-Oriented Programming 11


DCA1210: Object-Oriented Programming using C++

Polymorphism: Polymorphism in Object-Oriented Programming (OOP), which is derived from the


Greek word meaning "many forms/ multiple actions (Poly = Multiple, Morphing = Actions)."
Polymorphism allows a single function or operator to behave differently based on the context, such
as the type or number of arguments it receives i.e., the same operation can exhibit different behaviors
depending on the types of data involved.

For example, the operation of addition (+) can perform different tasks depending on the operands: it
can add two numbers to produce a sum, or if the operands are strings, it can concatenate them into a
single string. This flexibility is a key feature of polymorphism in OOP and is often implemented
through operator overloading, where operators are redefined to work with user-defined data types.

A specific type of polymorphism where a single function name is used to perform different tasks
depending on the number or type of arguments passed to it is called as function overloading.

Figure 5 illustrates this concept: a base class Shape defines a function Draw(), which is then
overridden in its derived classes like Circle, Box, and Triangle. Each of these derived classes provides
its specific implementation of the Draw() function, allowing the same function name to handle
different types of shapes.

This ability to use a single interface to represent different underlying forms is what makes
polymorphism a powerful tool in OOP. It allows for more flexible and maintainable code by enabling
objects to be treated as instances of their base class while still invoking behaviors specific to their
derived class. Polymorphism enhances the capability of OOP systems to handle different data types
and operations in a unified way, leading to more dynamic and adaptable code structures.

Figure 5: Polymorphism

Unit: 1 - Introduction to Object-Oriented Programming 12


DCA1210: Object-Oriented Programming using C++

Dynamic binding : in Object-Oriented Programming (OOP), it is also known as late binding. Binding,
refers to the process of linking a procedure call to the specific code that will be executed in response
to that call. Dynamic binding means that this linking process is deferred until runtime, rather than
being determined at compile time. This allows the program to decide which specific piece of code to
execute only when the program is actually running.

Dynamic binding is closely associated with polymorphism and inheritance. In polymorphism, a single
function call might behave differently depending on the actual object it is associated with at runtime.
This is useful when working with a class hierarchy where a base class reference can point to objects
of any derived class. The specific method that gets called depends on the dynamic type of the object
that the reference points to at the time of execution.

For example a draw() procedure in figure 5 illustrates dynamic binding. Imagine a base class that
defines a draw() function, and various derived classes (like Circle, Box, Triangle) that each provide
their own implementation of draw(). At runtime, when a draw() function is called on an object,
dynamic binding ensures that the version of draw() specific to the object's actual type (e.g., Circle or
Box) is executed. This flexibility allows for more dynamic and adaptable code, where the exact method
that gets executed is determined based on the actual object in use at runtime, rather than being fixed
at compile time.

Message passing: In Object-Oriented Programming (OOP), message passing is a fundamental aspect


of how objects interact within a program. In an OOP system, the program is composed of a collection
of objects, each of which is defined by a class. These objects communicate with each other by sending
and receiving messages, similar to how people exchange information.

The process of programming in an object-oriented language typically involves three key steps:
• creating classes that define objects and their behaviours,
• instantiating objects from these class definitions, and
• establishing communication among the objects through message passing.

Message passing allows objects to request actions from each other, which is conceptually similar to
sending a message in real life. When an object sends a message to another object, it is essentially
making a request for the execution of a specific procedure or function within the receiving object. This
involves specifying the name of the object to receive the message, the name of the function to be
invoked (the message), and any necessary information or arguments required for the function to
perform its task.

Unit: 1 - Introduction to Object-Oriented Programming 13


DCA1210: Object-Oriented Programming using C++

Figure 6: Message Passing

For example, in the figure 6, the message employee.salary(name) is shown as an illustration. Here,
the employee object is sending a message to invoke the salary function with the argument name. This
interaction results in the receiving object processing the request and returning the appropriate
information.

The concept of message passing is important because it models real-world interactions, making it
easier to build systems that simulate or reflect real-world scenarios. Objects in a program have a
lifecycle—they can be created, interact through message passing, and be destroyed. As long as an
object is alive, it can engage in communication with other objects, making message passing a dynamic
and vital component of OOP.

3.1. Characteristics of OOP


Object-Oriented Programming (OOP) was developed as a response to the limitations found in
procedural programming, where data and functions are often loosely coupled, leading to potential
issues such as accidental data modification and poor scalability.

The key motivation behind OOP is to enhance data security and program structure by treating data
as a fundamental element around which the program revolves. In OOP, data is closely tied to the
functions that operate on it, encapsulating it within objects and preventing unauthorized or
unintended modifications from other parts of the program. This encapsulation not only safeguards
the data but also makes the program more modular and easier to manage.

The characteristics below collectively make OOP a powerful and flexible programming paradigm,
especially for developing large and complex software systems.

• Emphasis on Data Rather Than Procedure: In OOP, the primary focus is on the data being
manipulated, as opposed to the procedural approach where the sequence of actions or functions

Unit: 1 - Introduction to Object-Oriented Programming 14


DCA1210: Object-Oriented Programming using C++

is prioritized. OOP ensures that data is the central element around which functions revolve,
safeguarding its integrity and ensuring that it is handled correctly within the program.
• Programs are Divided into Objects: OOP structures programs by breaking them down into
smaller, manageable units called objects. Each object encapsulates both data and the methods
(functions) that operate on that data, making the program modular and easier to manage.
• Characterization of Objects Through Data Structures: Objects are characterized by their data
structures, meaning that the way data is organized within an object defines its nature and
behavior. This design approach ensures that objects are self-contained entities that hold both the
data and the operations that manipulate it.
• Tying Functions with Data: Functions that work on an object's data are bound together within
the object's data structure. This tight coupling of data and methods ensures that the operations on
the data are restricted to those defined within the object, leading to better data integrity and
encapsulation.
• Data Hiding: OOP emphasizes the importance of hiding an object's internal data from external
functions. This concept, known as encapsulation, prevents unauthorized access and modification
of data, ensuring that it is only manipulated in controlled ways.
• Object Communication via Functions: While objects encapsulate their data, they are still
capable of interacting with one another. This interaction happens through functions or methods,
allowing objects to collaborate to achieve more complex behavior without directly exposing their
internal data.
• Ease of Adding New Data and Functions: One of the strengths of OOP is its flexibility. New data
and methods can be easily added to existing objects without disrupting the overall structure of
the program. This makes it easier to extend and maintain software over time.
• Bottom-Up Approach in Program Design: OOP often follows a bottom-up approach in program
design, where developers start by creating small, reusable objects and then combine them to build
more complex systems. This contrasts with the top-down approach in procedural programming,
where the focus is on defining the main functions and breaking them down into smaller tasks.

3.2. Benefits of Object-Oriented Programming (OOP)


The benefits of OOP are:

o Eliminating Redundant Code: Using inheritance, we can reuse existing code, which reduces the
need to write the same code multiple times.

Unit: 1 - Introduction to Object-Oriented Programming 15


DCA1210: Object-Oriented Programming using C++

o Building Programs Efficiently: OOP allows us to build programs using standard modules that
work together, saving time and improving productivity.
o Improving Security: Data hiding ensures that sensitive parts of a program are protected from
being accessed or modified by other parts of the program.
o Multiple Instances: OOP makes it possible to create multiple copies (instances) of an object that
can work simultaneously without affecting each other.
o Mapping Real-World Problems: It’s easy to relate objects in a program to real-world problems,
making the design more intuitive.
o Work Partitioning: OOP helps in dividing work among different parts of a project, making it
easier to manage.
o Detailed Design: The focus on data allows us to create more detailed and accurate models of real-
world problems.
o Scalability: Object-oriented systems can grow easily from small to large, adapting to more
complex requirements.
o Simplified Communication: Message passing between objects makes it easier to manage
interactions within the program and with external systems.
o Managing Complexity: OOP helps manage and reduce software's complexity, making it easier to
develop and maintain.

Unit: 1 - Introduction to Object-Oriented Programming 16


DCA1210: Object-Oriented Programming using C++

4. DIFFERENCE BETWEEN C AND C++


C is a general-purpose programming language known for its flexible and compact structure. Programs
written in C are typically composed of many small functions and focus on procedural programming.
C++, derived from C, extends the language by introducing object-oriented features, allowing for both
procedural and object-oriented programming.

The main difference between C and C++ is that C++ supports object-oriented programming (OOP),
which emphasizes writing programs that are more modular, reusable, and maintainable. OOP allows
for the packaging of data and functions into classes, promoting code reuse and better organization. In
contrast, C supports only procedural programming, which is less modular and harder to maintain in
large projects.

Key differences between C and C++ include:

• Programming Approach: C follows a top-down approach, while C++ supports a bottom-up


approach, particularly in OOP design.
• I/O Operations: C uses printf and scanf for input/output, while C++ uses cin and cout for the same.
• Function Declaration: In C++, all functions must be declared before they are used, usually with
prototypes. In C, functions can be used before being declared, although this is not considered good
practice.
• Structures: C structures are purely data containers, while C++ structures can include member
functions and access specifiers, making them more similar to classes.
• Underscores in Identifiers: In both C and C++, identifiers beginning with double underscores or
containing them are reserved for compiler use and should be avoided.
• Automatic Return in main(): In C++, an explicit return 0; is not necessary in main() as the
compiler automatically adds it, while in C, it is generally recommended to include it.

Unit: 1 - Introduction to Object-Oriented Programming 17


DCA1210: Object-Oriented Programming using C++

5. APPLICATIONS OF OBJECT-ORIENTED
PROGRAMMING (OOP)
OOP has become widely popular among software engineers and is seen as a significant advancement
in programming techniques. It is increasingly being used in various areas, especially in user interface
design, such as in the development of windowing systems.

Specific Applications of OOP:

a. Real-Time Systems:OOP is beneficial for developing real-time systems that require quick and
efficient processing of data and events.
b. Simulation and Modeling:OOP is used in simulation and modeling applications where complex
systems need to be represented and manipulated.
c. Object-Oriented Databases:OOP concepts are applied to create and manage databases that use
objects to represent data, enhancing the organization and retrieval of complex data structures.
d. Hypertext, Hypermedia, and Expert Text:OOP is utilized in creating hypertext systems,
hypermedia applications, and expert systems, which require flexible and dynamic data handling.
e. AI and Expert Systems:Artificial Intelligence (AI) and expert systems benefit from OOP, as it
helps in creating systems that can simulate human expertise and decision-making.
f. Neural Networks and Parallel Programming:OOP is instrumental in developing neural
networks and parallel programming, where the ability to handle complex data and processes is
crucial.
g. Decision Support and Office Automation Systems:OOP is used in building decision support
systems and automating office tasks, improving efficiency and productivity.
h. CIM/CAM/CAD Systems: Computer-Integrated Manufacturing (CIM), Computer-Aided
Manufacturing (CAM), and Computer-Aided Design (CAD) systems leverage OOP for designing,
manufacturing, and integrating complex industrial processes.

Unit: 1 - Introduction to Object-Oriented Programming 18


DCA1210: Object-Oriented Programming using C++

6. SUMMARY
Let us recapitulate the important points discussed in this unit:

Computer performs a variety of tasks with the help of programming languages. In 1980, Bjarne
Stroustrup, from Bell labs, began the development of the C++ language.

OOP is a bottom-up approach, focusing on objects that encapsulate both data and functions, which
helps in organizing programs more effectively. In OOP, data is treated as a critical element,
encapsulated within classes, thereby preventing it from being accessed or modified inadvertently.
This encapsulation enhances data security and integrity. The core concepts of OOP include
encapsulation, which ties data closely to the functions that operate on it within classes; objects and
classes, where problems are solved by interacting objects that are instances of classes; and data
hiding, which insulates data from direct access by other parts of the program. OOP also introduces
data abstraction, which focuses on essential features while hiding unnecessary details, making
complex systems easier to manage. Inheritance allows classes to inherit properties and behaviors
from other classes, promoting code reuse. Polymorphism enables functions or methods to take on
different forms, allowing the same function name to work with different types of data or objects.
Dynamic binding allows the exact code to be determined at runtime, providing flexibility, while
message passing facilitates communication between objects through method invocations.

The benefits of OOP are significant, with reusability being one of the most important advantages,
allowing developers to write modular code that can be reused in different parts of a program or in
different programs. OOP has gained widespread importance across various fields, particularly in real-
time business systems.

Unit: 1 - Introduction to Object-Oriented Programming 19


DCA1210: Object-Oriented Programming using C++

7. SELF-ASSESSMENT QUESTIONS
Multiple choice Questions
1 Which programming methodology uses a top-down approach?
a) Object-Oriented Programming
b) Procedural Programming
c) Functional Programming
d) Logic Programming
2 class is a __________?
a) A function that operates on data
b) A blueprint for creating objects
c) A type of loop
d) A method to manage memory
3 Which feature of OOP allows a class to inherit properties from another class?
a) Encapsulation
b) Abstraction
c) Polymorphism
d) Inheritance
4 Which language was the precursor to C++?
a) Python
b) Java
c) C
d) Fortran
5 What does encapsulation protect?
a) Code reusability
b) Data integrity
c) Memory allocation
d) Execution speed
6 Which of the following best describes polymorphism in OOP?
a) One function can have multiple forms
b) A class can have multiple parents
c) Objects can only have one method

Unit: 1 - Introduction to Object-Oriented Programming 20


DCA1210: Object-Oriented Programming using C++

d) A program can execute in multiple environments

7 What is the main focus of procedural programming?


a) Data
b) Objects
c) Functions
d) Inheritance
8 In OOP, an object's data is hidden and protected through which feature?
a) Abstraction
b) Inheritance
c) Encapsulation
d) Polymorphism
True or False:

9 C++ supports both procedural and object-oriented programming.

10 Inheritance in OOP allows objects to inherit properties from multiple classes at the same
time.
Fill in the Blanks:

11 The concept of ________ in OOP refers to an object taking on different forms.

12 What is the term for a function defined within a class?

Unit: 1 - Introduction to Object-Oriented Programming 21


DCA1210: Object-Oriented Programming using C++

8. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective

The various approaches and techniques used in the process of software


Programming
- development. They include procedural programming, object-oriented
Methodologies
programming, and others.
An early programming methodology that emphasizes a linear, top-down
Procedural
- approach to writing programs, focusing on procedures or functions to
Programming
operate on data.
Object-Oriented A programming paradigm that uses "objects" to represent data and
Programming - methods to model real-world entities and interactions, addressing the
(OOP) limitations of procedural programming.
The bundling of data and the methods that operate on that data within a
Encapsulation - single unit or class, restricting direct access to some of an object’s
components.
A mechanism in OOP where a new class is derived from an existing class,
Inheritance - inheriting its attributes and behaviors while allowing for additional
customization.

The ability of different classes to respond to the same function or method


Polymorphism -
call in a way that is specific to their class type.

The process of hiding the complex implementation details of a system and


Abstraction -
exposing only the necessary and relevant features to the user.

A principle in OOP where an object’s internal state is protected from


Data Hiding - outside access, ensuring that only authorized methods can interact with
its data.

A self-contained entity that contains data (attributes) and methods


Object -
(functions) that represent its behaviour.

A blueprint or template for creating objects, defining the data and


Class -
behaviour that the instantiated objects will have.

A function that is defined within a class and can operate on the data
Method -
contained within an object of that class.

Unit: 1 - Introduction to Object-Oriented Programming 22


DCA1210: Object-Oriented Programming using C++

Instance - A specific object created from a class.

The process by which objects communicate with each other in OOP by


Message Passing -
sending and receiving information through methods.

Unit: 1 - Introduction to Object-Oriented Programming 23


DCA1210: Object-Oriented Programming using C++

9. SAMPLE PROGRAMS
1. Simple C++ Program Without Using Classes
#include <iostream> // Modern header syntax
using namespace std;

int main()

{
cout << "Welcome to C++ programming"; // Output to console
return 0; // Indicate successful program termination
}

This program is a basic example of a C++ program that does not use any object-oriented concepts
such as classes or objects. It simply includes the necessary header file for input and output operations
and uses the main() function to print a message to the console. The cout object, which is part of the
standard C++ library, is used to output the string "Welcome to C++ programming".

When this program is run, it will display the following output on the console:
Welcome to C++ programming

2. Program to add two integers


#include <iostream> // Modern header syntax for I/O
using namespace std; // Allows usage of standard library components
// without std:: prefix

int main()
{ // Execution starts at main() function

int a, b, c;

cout << "\nProgram to add 2 integer values";


cout << "\nEnter the values of integers a & b: ";

cin >> a >> b; // Read input values into a and b

c = a + b; // Add the values of a and b, store in c

// Output the values of a, b, and c


cout << "\nThe value of a is " << a;

Unit: 1 - Introduction to Object-Oriented Programming 24


DCA1210: Object-Oriented Programming using C++

cout << "\nThe value of b is " << b;


cout << "\nThe sum (c) of a and b is " << c << endl;

return 0; // Indicate successful program termination


}

The above C++ program is a simple example designed to demonstrate how to perform basic
arithmetic operations, specifically the addition of two integers, and how to interact with the user
through input and output operations. The program begins by including the necessary header file
which is part of the C++ Standard Library. It provides facilities for input and output (I/O), like cin for
input and cout for output.

However, it should be noted that in modern C++, iostream is used instead of iostream.h.

The program execution starts with the main() function, which is the entry point for any C++ program.
Inside this function, three integer variables—a, b, and c—are declared. These variables are used to
store the integers that the user will input (a and b) and their sum (c).

The program then uses the cout statement to display messages on the screen, informing the user
about the program's purpose (to add two integers) and prompting them to enter the values for a and
b. The cin statement is employed to capture the user’s input, reading the values entered by the user
and storing them in the variables a and b.

Once the input values are received, the program calculates the sum of a and b by using the expression
c = a + b;, storing the result in the variable c. The program then outputs the values of a, b, and c using
additional cout statements, displaying the input values and their calculated sum.

Finally, the program reaches the end of the main() function, at which point it terminates.

When the program is executed with inputs 5 and 10.

The output will be:


Program to add 2 integer values
Enter the values of integers a & b
5 10
The value of a is 5
The value of b is 10
The sum (c) of a and b is 15

3. C++ Program to calculate the area of a rectangle

Unit: 1 - Introduction to Object-Oriented Programming 25


DCA1210: Object-Oriented Programming using C++

#include<iostream> // Include the input-output stream library


using namespace std;

int main() {
// Declare variables for length, width, and area
double length, width, area;

// Prompt the user to enter the length of the rectangle


cout << "Enter the length of the rectangle: ";
cin >> length; // Read the length

// Prompt the user to enter the width of the rectangle


cout << "Enter the width of the rectangle: ";
cin >> width; // Read the width

// Calculate the area of the rectangle


area = length * width;

// Output the area of the rectangle


cout << "The area of the rectangle is: " << area << endl;

return 0; // Return 0 to indicate successful completion


}

The above C++ program is a straightforward example designed to calculate the area of a rectangle
based on user input for the length and width. The program begins by including the iostream library,
which is essential for handling input and output operations in C++. By using the using namespace std;
directive, the program allows for easier access to standard library objects like cin and cout without
needing to prefix them with std::. The program's execution starts with the main() function, where
three variables—length, width, and area—are declared. These variables are of type double to
accommodate the possibility of decimal values.

The program then prompts the user to enter the length and width of the rectangle using cout
statements, and it captures these values using cin, storing them in the length and width variables. The
area of the rectangle is calculated by multiplying the length and width, with the result stored in the
area variable. After the calculation, the program outputs the computed area to the user with a clear

Unit: 1 - Introduction to Object-Oriented Programming 26


DCA1210: Object-Oriented Programming using C++

message indicating the result. The program concludes with a return 0; statement, signaling successful
execution.

The output will be:


Enter the length of the rectangle: 5
Enter the width of the rectangle: 10
The area of the rectangle is: 50

4. C++ Program to Enter name and age and it will Display the Collected Information.
#include <iostream> // Required for cin and cout
using namespace std;
int main() {
int age; // Variable to store the user's age
string name; // Variable to store the user's name
// Prompt the user to enter their name
cout << "Enter your name: ";
cin >> name; // Take input and store it in the variable 'name'
// Prompt the user to enter their age
cout << "Enter your age: ";
cin >> age; // Take input and store it in the variable 'age'
// Display the collected information
cout << "Hello " << name << "You are " << age << " years old." << endl;
return 0;
}

This C++ program is designed to collect and display the user's name and age. It begins by including
the <iostream> header file, which provides functionality for input and output operations using cin
and cout. The using namespace std; statement allows the program to avoid prefixing standard library
objects with std::.Inside the main() function, two variables are declared: name to store the user's
name, and age to store the user's age. The program prompts the user to enter their name by printing
the message "Enter your name: " to the console, followed by using cin to capture the user's input into
the name variable.

Similarly, the program prompts the user to enter their age, storing the input in the age variable using
cin. Finally, the program outputs a personalized message that includes the user's name and age using
cout.

Unit: 1 - Introduction to Object-Oriented Programming 27


DCA1210: Object-Oriented Programming using C++

If the user's name is “Vijay” and age is 20. The program first prompts for the user's name and stores
"Vijay" in the name variable. Then, it prompts for the user's age and stores "20" in the age variable.
Finally, it displays the message "Hello Vijay You are 20 years old." by combining the stored values
with the text in the cout statement.

The output will be:


Enter your name: Vijay
Enter your age: 20
Hello Vijay You are 20 years old.

5. C++ Program : Celsius to Fahrenheit Conversion

#include <iostream> // Required for cin and cout


using namespace std;
int main() {
float celsius, fahrenheit; // Declare variables for Celsius and Fahrenheit
// Prompt the user to enter the temperature in Celsius
cout << "Enter temperature in Celsius: ";
cin >> celsius; // Take input for Celsius temperature

// Convert Celsius to Fahrenheit using the formula: (Celsius * 9/5) + 32


fahrenheit = (celsius * 9/5) + 32;

// Display the result


cout << celsius << " Celsius is equal to " << fahrenheit << " Fahrenheit." << endl;
return 0;
}

This C++ program converts a temperature from Celsius to Fahrenheit. It first prompts the user to
enter a temperature in Celsius and stores the input in the variable celsius. Then, it uses the formula
(Celsius * 9/5) + 32 to convert the value to Fahrenheit and stores the result in the variable fahrenheit.
The program finally displays the conversion result by outputting a message in the format: "[celsius]
Celsius is equal to [fahrenheit] Fahrenheit." If the user enters 25 as the Celsius :-

The output will be:


Enter temperature in Celsius: 25
25 Celsius is equal to 77 Fahrenheit.

Unit: 1 - Introduction to Object-Oriented Programming 28


DCA1210: Object-Oriented Programming using C++

10. TERMINAL QUESTIONS


1. Outline the evolution of programming methodologies from procedural programming to object-
oriented programming.
2. What is polymorphism in OOP? Provide an example to illustrate your explanation.
3. Describe the process of message passing in OOP and its significance.
4. Explain the difference between abstraction and encapsulation in OOP.
5. What are the primary applications of Object-Oriented Programming? Give examples of fields
where OOP is widely used.
6. Provide a detailed comparison between C and C++ focusing on their support for procedural and
object-oriented programming.
7. Analyse the benefits and challenges of implementing Object-Oriented Programming in large-scale
software projects.
8. Explain in detail the impact of OOP on software design and architecture, focusing on
maintainability, scalability, and reusability.
9. Discuss the key characteristics of Object-Oriented Programming (OOP) in detail, with examples.
10. Explain how inheritance, polymorphism, and encapsulation work together in OOP to create
modular and flexible software systems.

Unit: 1 - Introduction to Object-Oriented Programming 29


DCA1210: Object-Oriented Programming using C++

11. ANSWERS
Self-Assessment Questions
1. Procedural Programming
2. A blueprint for creating objects
3. Inheritance
4. C
5. Data integrity
6. One function can have multiple forms
7. Functions
8. Encapsulation
9. True
10. False
11. Polymorphism
12. Method

Terminal Questions Answers


1. Refer to section 1.2
2. Refer to section 1.3
3. Refer to section 1.3
4. Refer to section 1.3
5. Refer to section 1.5
6. Refer to section 1.4
7. Refer to section 1.3.2
8. Refer to section 1.3 and 1.3.1
9. Refer to section 1.3.1
10. Refer to section 1.3

Unit: 1 - Introduction to Object-Oriented Programming 30


DCA1210: Object-Oriented Programming using C++

12. REFERENCES
1. E Balagurusamy, “Object-Oriented Programming with C++”, 8th edition, 2020, Tata McGraw Hill
Publications.
2. Object-Oriented Programming Using C++, By B. Chandra, CRC Press.
3. Starting Out with C++: From Control Structures Through Objects, Global Edition, by Tony Gaddis,
Pearson Education.

Unit: 1 - Introduction to Object-Oriented Programming 31


DCA1210: Object-Oriented Programming using C++

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 2

DCA1210
OBJECT - ORIENTED PROGRAMMING
Unit: 2 - Basic Structure of C++ USING C++ 1
DCA1210: Object-Oriented Programming using C++

Unit – 2
Basic Structure of C++

Unit: 2 - Basic Structure of C++ 2


DCA1210: Object-Oriented Programming using C++

TABLE OF CONTENTS

Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
5-6
1.1 Objectives - -
2 An Overview of the C++ program - -

2.1 Program features - -

2.2 Comments - -

2.3 Output Statement/Output operator 1 - 7 - 15

2.4 The Iostream File i, ii -

2.5 Namespace - -

2.6 Return Type of main() Function - -


3 More C++ Codes - -

3.1 Variables1 - -
16 - 18
3.2 Input Operator 2 -

3.3 Cascading of I/O Operators - -


4 A sample program with Class - - 19 - 20
5 Structure of C++ Program 3, 4 - 21 - 22
6 Creating the Source File - - 23
7 Compiling and linking - - 24 - 25
8 Basic Components of a C++ Program - -

8.1 Data types 5, iii -


- - 26 - 29
8.2 Variables
Token of C++: Identifiers, Keywords, Constants, - -
8.3
Operators
9 Summary - - 30
10 Self-Assessment Questions - 1 31 - 33
11 Glossary - - 34 - 35

Unit: 2 - Basic Structure of C++ 3


DCA1210: Object-Oriented Programming using C++

12 Terminal Questions - - 36
13 Answers - - 37
14 References - - 38

Unit: 2 - Basic Structure of C++ 4


DCA1210: Object-Oriented Programming using C++

1. INTRODUCTION
In the previous unit 1, learners have studied the Evolution of Programming Methodologies, tracing
the shift from procedural to object-oriented approaches. Learners were introduced to Object-
Oriented Programming (OOP) and its core features, delving into the Characteristics of OOP, such as
encapsulation, inheritance, and polymorphism, and discussed the significant Benefits of Object-
Oriented Programming, including enhanced code reusability and maintainability. Then learners also
examined the key Differences between C and C++, highlighting how C++ extends C with OOP
capabilities and the various Applications of OOP, demonstrating its versatility in modern software
development.

In this unit, learners will learn the basics of C++ programming, starting with an Overview of a C++
Program where learners will be introduced to the structure of a simple C++ program, explaining key
components like the main() function and how a C++ program is organized.

Learners will also explore important Program Features, such as the flexibility of C++ syntax and its
similarities with the C language. They'll also learn about Comments, which are used to make the code
more understandable, and how to use Output Statements/Operators to display information on the
screen, then they learn the Iostream File, which is essential for handling input and output in C++.
Learners will be introduced to Namespaces, which help prevent conflicts in large programs, and
understand the role of the Return Type of the main() Function in signaling whether a program ran
successfully. The unit will guide students through Creating the Source File and the steps involved in
Compiling and Linking a C++ program, turning code into an executable file. Finally, learners will
review the Basic Components of a C++ Program, focusing on Data Types and Variables, which are
fundamental to programming in C++.

To study these topics, learners have to start by grasping the fundamental concepts like program
structure, data types, and operators, as these are the building blocks of programming. Practice writing
simple programs to reinforce understanding, especially focusing on how variables, input/output
operations, and the main function work. Use comments to document your code, making it easier to
understand and debug. Gradually advance to more complex topics like classes, namespaces, and
compiling processes, ensuring you apply each concept through hands-on coding to solidify your
knowledge.

Unit: 2 - Basic Structure of C++ 5


DCA1210: Object-Oriented Programming using C++

1.1. Objectives
After studying this unit, you should be able to:
• Explain the basic structure and flow of a C++
program.
• Apply C++ program features effectively in code
writing.
• Describe the data types of a C++ program
• Define the terms ‘keyword’, ‘constant’, ‘identifiers’
and ‘operators’
• Dxplain the process of compilation and execution.

Unit: 2 - Basic Structure of C++ 6


DCA1210: Object-Oriented Programming using C++

2. AN OVERVIEW OF THE C++ PROGRAM


Understanding the structure of a simple C++ program is essential for anyone beginning to learn the
language, as it provides the foundation for writing more complex applications. A typical C++ program
comprises several key components, each serving a specific purpose.

A simple C++ program begins with preprocessor directives, such as #include<iostream>, which allow
the program to use functions from the standard C++ library. This is followed by the main() function,
which is the entry point of any C++ program. The main() function is where the execution of the
program begins and ends. Inside this function, the programmer typically declares variables that store
data that the program will manipulate.

The program may also include statements that interact with the user, such as input, and output
operations handled by cin and cout. These operations allow the program to receive data from the user
and display results back to them. Arithmetic operations or other types of processing are performed
on the data, and the results are often stored in variables for later use or output.

The structure of a simple C++ program is designed to be logical and easy to follow. It typically consists
of a sequence of statements that are executed in the order they are written, allowing the program to
perform its intended tasks.

Example 1:
#include <iostream> // include header file
using namespace std;
int main() {
cout << "C++ is better than C.\n"; // C++ statement
return 0;
} // End of example

The C++ program in example 1 is a simple program designed to demonstrate basic input/output
operations using the standard C++ library. The program begins with including the iostream header
file using #include <iostream>. This header file is essential for handling input and output streams,
such as displaying text on the screen using the cout object.

The using namespace std; directive is included to allow the program to use names from the standard
library (like cout) without requiring the std:: prefix, simplifying the code and making it more readable.

Unit: 2 - Basic Structure of C++ 7


DCA1210: Object-Oriented Programming using C++

The program’s execution starts with the main() function, which is the entry point for any C++
application. Within this function, a single statement is executed: cout << "C++ is better than C.\n";.
This line uses the cout object to print the string "C++ is better than C." to the console. The \n at the
end of the string is a newline character, which moves the cursor to the next line after printing the text.

Finally, the program concludes with the return 0; statement, which indicates that the program has
successfully completed its execution. The value 0 is returned to the operating system to signal that
the program ran without errors.

2.1. Program Features:


• Like a C program, a C++ program consists of a collection of functions. Each program must have a
main() function, which is where the execution begins.
• Every C++ program must have a main() function, as it is the entry point for the program's execution.
• C++ is a free-form language, allowing flexibility in the placement of whitespace, returns, and other
formatting elements. The compiler generally ignores carriage returns and spaces.
• In C++, like in C, statements are terminated with a semicolon (;).

2.2. Comments:
• C++ introduces a new comment symbol, //, which is used for single-line comments. Everything
following // on that line is treated as a comment and is ignored by the compiler.
• The // symbol is used to create single-line comments. These comments begin with // and extend
to the end of the line. They are useful for adding short explanations within the code.
• Multi-line comments can also be created using // by placing it at the beginning of each line.
However, this is more cumbersome compared to using the traditional C-style comment symbols.
• The traditional C-style comment symbols /* and */ are still valid in C++ and are more suitable for
multi-line comments. This method allows for easier commenting across multiple lines without
the need to place // on each line. Comments can be placed anywhere within the code. However,
the // style comment cannot be placed in the middle of a line of code as it will comment out the
remainder of that line.

Below example explains how to use both // for single-line comments and /* ... */ for multi-line
comments.

Single-Line Comment Example:

Unit: 2 - Basic Structure of C++ 8


DCA1210: Object-Oriented Programming using C++

// This is an example of
// C++ program to illustrate
// Some of its features

Example of multi-line comments using C-style symbols:


/* This is an example of
C++ program to illustrate
some of its features */

2.3. Output Statement/Output operator:


• The only statement in the referenced program is an output statement:
cout << "C++ is better than C.";. This statement displays the string inside the quotation marks on
the screen.
• The statement introduces two important C++ features: cout and <<. The cout object (pronounced
as "C out") is a predefined object in C++ that represents the standard output stream, typically the
screen.
• The cout object is used to output data to the standard output device, the monitor.
• The << operator is the insertion operator or the "put to" operator. It sends the data on its right (in
this case, the string "C++ is better than C.") to the object on its left (cout), which then displays it
on the screen.
• The << operator is also known as the bitwise left-shift operator in other contexts. However, in the
context of cout, it is overloaded when performing the insertion operation. This is an example of
operator overloading, where an operator is given a different meaning based on the context.
• While C++ allows using the printf() function from C for displaying output, the cout and << notation
is preferred in C++ to maintain its object-oriented spirit.

Unit: 2 - Basic Structure of C++ 9


DCA1210: Object-Oriented Programming using C++

Figure 1: Sending data to the output stream using the insertion operator (<<).

Figure 1 effectively demonstrates the flow of data from a variable to the output device (screen) using
the cout object and the << operator in C++.

The cout object is shown as the receiving entity for the output data. It directs the data to the standard
output device, typically the screen.

The insertion operator (<<) is shown as the connector between the data (in this case, the string "C++")
and the cout object. It sends the data from the variable on its right to the cout object on its left. The
variable, which contains the string "C++", is on the right side of the insertion operator. The figure
shows that this data is passed through the insertion operator to the cout object. The final output is
displayed on the screen, as indicated by the arrow from cout to the screen. The data passed to cout is
ultimately shown on the display, which in this example would be the text "C++".

2.4. The iostream File:


The #include <iostream> directive is used to include the contents of the iostream file in a C++
program. This directive instructs the preprocessor to add the necessary code from the iostream file
into the program before compilation begins. The iostream file contains declarations for standard
input/output stream objects like cout and the operator <<. These are essential for performing input
and output operations in a C++ program. In earlier versions of C++, a header file named iostream.h
was used instead of iostream. The text mentions that iostream.h was commonly used before the
introduction of ANSI C++ standards. It is noted that if a compiler does not support ANSI C++ features,

Unit: 2 - Basic Structure of C++ 10


DCA1210: Object-Oriented Programming using C++

the iostream.h header file should be used. This is relevant for older compilers that have not been
updated to support the newer standards.

Importance of Including iostream:


The iostream header file should be included at the beginning of all programs that require
input/output operations. Without it, the program would not recognize commands like cout and cin.

The naming conventions for header files can vary depending on the compiler or the implementation.
Some implementations may use header files with extensions like .hpp (e.g., iostream.hpp) or .hxx (e.g.,
iostream.hxx). It is important to include the appropriate header file based on the compiler being used
and the specific requirements of the program. This ensures compatibility and correct program
functionality.

Tables 1 and 2 list the standard library header files needed in C++ programs. It mentions that header
files with a .h extension are considered "old style" and should be used with older compilers. using the
correct header files is crucial for maintaining compliance with ANSI (American National Standards
Institute) C++ standards, which represent the modern C++ standard.

Table 1: Commonly used old-style header files

Header File
Contents and Purpose New Version
(Old Version)

Includes macros and information useful for debugging


<assert.h> <cassert>
programs.
Provides functions to test character types and convert
<ctype.h> <cctype>
between uppercase and lowercase.

<float.h> Defines system-specific limits for floating-point numbers. <cfloat>

<limits.h> Defines system-specific limits for integer data types. <climits>

<math.h> Supplies function prototypes for mathematical operations. <cmath>

Offers standard input/output function prototypes and related


<stdio.h> <cstdio>
information.

Provides functions for number conversion, memory


<stdlib.h> <cstdlib>
management, and various utility operations.

Unit: 2 - Basic Structure of C++ 11


DCA1210: Object-Oriented Programming using C++

Header File
Contents and Purpose New Version
(Old Version)

Contains functions for handling C-style strings and their


<string.h> <cstring>
operations.
Includes functions and types for working with time and date
<time.h> <ctime>
values.
Provides function prototypes for handling standard input and
<iostream.h> <iostream>
output operations.

<iomanip.h> Contains stream manipulators for formatting data streams. <iomanip>

Provides functions for reading from and writing to files on


<fstream.h> <fstream>
disk.

Table 2: Commonly used old-style header files

Header File Contents and Purpose (Paraphrased)


Provides classes and functions commonly utilized across
<utility>
various standard library headers.
<vector>, <list>, <deque>, Includes classes that implement standard library containers,
<queue>, <set>, <map>, <stack>, used for storing and managing data during program
<bitset> execution.
Contains classes and functions used for implementing
<functional>
algorithms in the standard library.
Provides classes and functions for dynamic memory
1<memory>
allocation in standard library containers.
Offers classes designed for handling and manipulating data
<iterator>
stored in standard library containers.
Contains functions that help with the manipulation and
<algorithm>
processing of data in standard library containers.
Includes classes that handle exceptions, allowing for robust
<exception>, <stdexcept>
error handling in programs.
Provides the definition for the standard library string class,
<string>
which is used for string manipulation and processing.
Contains functions and classes for string stream operations,
<sstream> enabling input and output processing from strings in
memory.

Unit: 2 - Basic Structure of C++ 12


DCA1210: Object-Oriented Programming using C++

Offers classes and functions primarily for processing data in


<locale> a format suitable for different languages, including sorting
and formatting.
Defines classes that set numerical limits on data types
<limits>
specific to each computer platform.
Includes classes that assist in identifying data types at
<typeinfo>
runtime, essential for type checking and casting operations.

2.5. Namespace:
The concept of "namespace" was introduced by the ANSI C++ standards committee. It defines a scope
for the identifiers (such as variables, functions, and classes) used within a program to prevent name
conflicts. The standard namespace in C++ where the ANSI C++ standard class libraries are defined is
std. To use the identifiers defined within the std namespace, you need to include the directive using
namespace std; in your program. Including the using namespace std; directive allows the program to
access all identifiers within the std namespace without needing to prefix them with std::. This makes
the code cleaner and easier to read. All ANSI C++ programs must include this directive to ensure that
the standard library identifiers are available in the global scope. Namespaces help organize code and
prevent conflicts between identifiers in large projects.

Program without namespaces:


#include <iostream>
using namespace std;
void display() {
cout << "Hello " << endl;
}
void display() { // Error: Duplicate function declaration
cout << "Hello everyone" << endl;
}
int main() {
display();
return 0;
}

Unit: 2 - Basic Structure of C++ 13


DCA1210: Object-Oriented Programming using C++

The main problem in this program is that there are two functions with the same name, display(), in
the same scope (global scope). In C++, every function must have a unique name within its scope so
that the compiler can easily identify it. Since both display() functions are defined globally, the
compiler gets confused when calling display() in the main() function. It doesn’t know which one to
use, which leads to a "duplicate function declaration" error.

This issue happens because there is no namespace or any other way to separate the functions. To fix
this, we can either give the functions different names or place them inside different namespaces to
avoid confusion.

Program with namespaces:


#include <iostream>
using namespace std;
namespace firstNamespace {
void display() {
cout << "Hello from firstNamespace!" << endl;
}
}
namespace secondNamespace {
void display() {
cout << "Hello from secondNamespace!" << endl;
}
}
int main() {
firstNamespace::display();
// Calls display from firstNamespace
secondNamespace::display();
// Calls display from secondNamespace
return 0;
}

Program Output:
Hello from firstNamespace!
Hello from secondNamespace!

Unit: 2 - Basic Structure of C++ 14


DCA1210: Object-Oriented Programming using C++

In this program, namespaces are used to prevent naming conflicts by placing two display() functions
in separate namespaces: firstNamespace and secondNamespace. Since both functions have the same
name but exist in different namespaces, the compiler can distinguish between them. The main()
function calls firstNamespace::display() and secondNamespace::display() using the scope
resolution operator (::), ensuring the correct function is executed.

Compared to the previous example, where both display() functions were in the same global scope,
causing a duplicate function declaration error, this approach avoids conflicts. Without namespaces,
the compiler gets confused about which function to call. By using namespaces, we can organize code
better and prevent naming clashes, especially in large projects or when integrating multiple libraries.

2.6. Return Type of main() Function:


In C++, the main() function returns an integer (int) type value to the operating system. This return
value typically indicates whether the program executed successfully or encountered an error. It is
essential that every main() function in C++ ends with a return 0; statement to return an integer value
explicitly. If this is omitted, a warning or an error may occur, depending on the compiler. The default
return type for all functions in C++ is int. For the main() function, if the return type is not specified,
the compiler may still run the program but with a warning.

Example:
main()
{
……….
……….
……….
}

The above example showing how a main() function without a specified return type and return
statement might still compile but will generate a warning.

Unit: 2 - Basic Structure of C++ 15


DCA1210: Object-Oriented Programming using C++

3. MORE C++ CODES


1. C++ program to find the average of two numbers.
#include <iostream>
using namespace std;
int main()
{
float number1, number2, sum, average;

cout << "Enter two numbers: "; // prompt


cin >> number1; // Reads numbers
cin >> number2; // from keyboard

sum = number1 + number2;


average = sum / 2;

cout << "Sum = " << sum << "\n";


cout << "Average = " << average << "\n";

return 0;
}

The output of Program is:


Enter two numbers: 6.5 7.5
Sum = 14
Average = 7

3.1. Variables:
• The above program uses four variables: number1, number2, sum, and average.
• These variables are declared as type float, which means they can hold decimal numbers.
• The variables are declared with the statement:
• float number1, number2, sum, average;
• All variables must be declared before they are used in the program. This is a fundamental rule in
C++ to ensure that the program knows what type of data each variable will store.

Unit: 2 - Basic Structure of C++ 16


DCA1210: Object-Oriented Programming using C++

3.2. Input Operator:


The statement:
cin >> number1;

This is an input statement that prompts the program to wait for the user to type in a number. The
number entered by the user is then stored in the variable number1. The cin (pronounced "C in") is a
predefined object in C++ representing the standard input stream, typically the keyboard. It is used to
receive input from the user. The >> operator, also known as the extraction or "get from" operator, is
used to extract the input from the keyboard and assign it to the variable on its right. In this case, the
value typed by the user is assigned to number1. This operator corresponds to the scanf() function in
C and can also be overloaded in C++.

Figure 2 explains how the cin object and the extraction operator work together to take input from the
user and store it in a program's variable. The figure shows the cin object, which is connected to the
keyboard. This indicates that cin is used to receive input from the keyboard.

The operator >> is depicted as an arrow pointing from the cin object towards a variable. This visually
represents the process of data extraction, where the value entered from the keyboard is transferred
to the variable.

The figure shows a variable receiving the value 45.5, indicating that this value has been input by the
user through the keyboard and is now stored in the variable.

Figure 2: Input using extraction operator

3.3. Cascading of I/O Operators:


The insertion operator << is used repeatedly in statements to print multiple results to the output
(console).

For example:

Unit: 2 - Basic Structure of C++ 17


DCA1210: Object-Oriented Programming using C++

cout << "Sum = " << sum << "\n";

This statement first sends the string "Sum = " to the cout object, then sends the value of the variable
sum, and finally, it sends the newline character "\n" to move the cursor to the next line.

The technique of using multiple << operators in a single statement is called cascading. Cascading
allows you to combine multiple outputs into a single statement. When cascading output operators, it
is important to include necessary spaces or newline characters between different items to ensure the
output is correctly formatted.

The below statements explain how the last two statements can be combined into one using cascading:

cout << "Sum = " << sum << "\n"


<< "Average = " << average << "\n";

This single statement provides two lines of output, one for the sum and another for the average.

If you want to print the sum and average on the same line, you can modify the statement slightly as
shown below:

cout << "Sum = " << sum << ", "


<< "Average = " << average << "\n";

The output will be:


Sum = 14, Average = 7

Cascading Input Operator (>>):


The content also explains that cascading can be used with the input operator >>

cin >> number1 >> number2;

This statement assigns the first input value to number 1 and the second input value to number 2 in
the order in which the user enters them.

For example, if the user inputs 10 20, 10 will be assigned to number 1, and 20 will be assigned to
number 2.

Unit: 2 - Basic Structure of C++ 18


DCA1210: Object-Oriented Programming using C++

4. A SAMPLE PROGRAM WITH CLASS


Classes are a major feature of C++ and provide a way to bind together data and functions that operate
on that data. This concept is similar to structures in C but more powerful because it includes data and
functions. Like structures in C, classes are user-defined data types in C++ i.e., you can define the data
types that suit the needs of your program.

#include <iostream>
using namespace std;

class person
{
char name[30];
int age;

public:
void getdata(void);
void display(void);
};

void person::getdata(void)
{
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
}

void person::display(void)
{
cout << "\nName: " << name;
cout << "\nAge: " << age;
}

int main()
{

Unit: 2 - Basic Structure of C++ 19


DCA1210: Object-Oriented Programming using C++

person p;
p.getdata();
p.display();
return 0;
}

The above example shows how to use a class in a C++ program.

The class in the example is named person.

Data Members:
The class person has two data members:
o char name[30]; - An array of characters to store the name of the person.
o int age; - An integer to store the age of the person.

Member Functions:
The class has two member functions:
o void getdata(void); - A function to input data (name and age) from the user.
o void display(void); - A function to display the data (name and age).

Defining Member Functions:


o getdata() Function: This function prompts the user to enter their name and age, which are
then stored in the name and age data members of the class.
o display() Function: This function outputs the name and age stored in the class to the console.

Using the Class in main():


In the main() function:
o An object p of the class person is created.
o The getdata() function is called using the object p to input the name and age.
o The display() function is called using the object p to display the name and age.

Program Output:
The output of Program is shown, where:
o The user is prompted to enter their name (Ravinder) and age (30).
o The program then outputs:
Name: Ravinder
Age: 30

Unit: 2 - Basic Structure of C++ 20


DCA1210: Object-Oriented Programming using C++

5. STRUCTURE OF C++ PROGRAM


It is typically recommended to structure a program by dividing it into three distinct files. The class
declarations are contained within a header file, while the implementations of the member functions
are placed in a separate file. This method allows the programmer to differentiate between the abstract
interface of the class (class definition) and the specific implementation details (member function
definitions). The main program that utilizes the class is then stored in a third file, which incorporates
the first two files along with any other necessary files.

In figure 3 it is clearly explained that,

Header File: This file contains the class declarations. It defines the blueprint of the class, including
its data members and member functions but does not include the implementation of the functions.

Implementation File: This file contains the definitions of the member functions declared in the
header file. Here, the actual code for the member functions is written, specifying how each function
operates.

Main Program File: This file contains the main() function, which serves as the entry point of the
program. This file uses the class and its member functions to perform the necessary tasks. It includes
the header file and, indirectly, the implementation file.

Separation of Interface and Implementation: This approach allows for a clear separation between
the interface and the implementation:

o Interface (Class Definition): The header file provides an abstract specification of the class,
showing how it can be used without exposing the details of how it works.
o Implementation (Member Function Definitions): The implementation file handles the details
of how the member functions operate, which are hidden from the user of the class.

Benefits:
• By separating the class interface from its implementation, this structure promotes modularity
and encapsulation. It allows different parts of the program to be developed, tested, and
maintained independently.

Unit: 2 - Basic Structure of C++ 21


DCA1210: Object-Oriented Programming using C++

• The main program file can include the class and use its functionality without needing to know
how the class is implemented internally. This makes the code more maintainable and easier to
manage in large projects.

Figure 3: Structure of a C++ Program

We can organize a C++ program into different files is based on the client-server model as shown in
figure 4.

Server: The server is represented by the class definition and its member functions. This "server"
provides services (functions) that can be used by other parts of the program.

Client: The client is represented by the main function program, which utilizes the services provided
by the server. The main function accesses the server through the public interface (i.e., the public
member functions) of the class.

Interaction: The client (main function) makes requests to the server (class functions) to perform
operations. The server executes these requests and returns the results to the client.

Figure 4: Client Server Model

Unit: 2 - Basic Structure of C++ 22


DCA1210: Object-Oriented Programming using C++

6. CREATING THE SOURCE FILE


• C++ programs can be written using any standard text editor. The text editors mentioned include:
o UNIX systems: Editors like vi or ed can be used to create and edit source code.
o DOS systems: Editors like Edlin or other available editors can be used. It also mentions
that word processors can be used to avoid formatting issues that interfere with code,
provided they operate in a non-document mode.

• Integrated Development Environments (IDEs): Some systems, such as Turbo C++, provide an
integrated environment specifically designed for developing and editing C++ programs. These
environments often include tools for compiling and debugging, making the development process
more streamlined.

• File Extensions for C++ Source Files: C++ source files must have the correct file extension to
indicate that they contain C++ code. The file extension varies depending on the system and
compiler:
o Common file extensions for C++ source files include .c, .C, .cc, .cpp, and .cxx.
o Turbo C++ and Borland C++: Typically use .c for C programs and .cpp for C++ programs.
o Zortech C++: Uses the .cxx extension.
o UNIX AT&T version: Uses .C (with a capital 'C') and .cc as extensions.

• Consulting Manuals: It’s recommended to consult the operating system or compiler manuals to
determine the correct file name extension to use for C++ source files. This is important to ensure
that the files are recognized correctly by the compiler and that the code can be compiled and
executed without issues.

Unit: 2 - Basic Structure of C++ 23


DCA1210: Object-Oriented Programming using C++

7. COMPILING AND LINKING


The process of compiling (turning source code into an object file) and linking (combining object files
into an executable program) depends on the operating system being used.

1. Unix AT&T C++:


a. Compiling C++ Programs:
On UNIX systems, the process of compiling a C++ program is similar to compiling a C program. The
key difference is the command used:

• C++ Compilation: The command CC (uppercase) is used to compile C++ programs.


• C Compilation: The command cc (lowercase) is used to compile C programs.

Example:
o To compile a C++ source code file named example.C, you would use the following command:
CC example.C

o This command compiles the example.C file into an object file named example.o, and then links
it with the necessary library functions to produce an executable file. The default name for this
executable file is a.out.

b. Compiling Multiple Files:


If a program is spread across multiple files, they can be compiled together using a command like:
CC file1.C file2.o

This command compiles file1.C and links it with the already compiled object file file2.o. This is
useful when only one file has been modified, as it avoids recompiling the entire program.

2. Turbo C++ and Borland C++:


Turbo C++ and Borland C++ offer an integrated program development environment under MS-DOS.
They provide a built-in editor and a menu bar with options such as:

• File: For creating and saving source files.


• Edit: For editing the source files.
• Compile: For compiling the program.
• Run: For executing the compiled program.

Unit: 2 - Basic Structure of C++ 24


DCA1210: Object-Oriented Programming using C++

The Run option can be used to compile, link, and execute the program in one step, without needing to
manually compile the source code beforehand.

Turbo C++ is mentioned as one of the most popular compilers, and the creation and execution of
programs using Turbo C++ are discussed in more detail in Appendix B (not provided in the image).

3. Visual C++:
Visual C++ is an application development system from Microsoft that runs under Windows. It is a
visual programming environment that allows users to create basic program components through:

Menu choices, buttons, icons, and other predefined methods.

The development and execution of C++ programs using Visual C++ under Windows are briefly
discussed in Appendix C (not provided in the image).

Unit: 2 - Basic Structure of C++ 25


DCA1210: Object-Oriented Programming using C++

8. BASIC COMPONENTS OF A C++ PROGRAM


We have already learnt that C++ is a superset of C. At the basic level, the programs look similar in both
C and C++. Every statement in C++ ends with a semicolon (;). All the reserved words have to be written
in the small case,

8.1. Data types


A data type in a programming language is a set of data with values having predefined characteristics.
Both C and C++ compilers support a set of built-in data types, also referred to as basic or
fundamental data types. These data types are the building blocks for any program and include types
like int, char, float, double, etc.

The basic data types can be modified using several modifiers to suit various programming needs.
These modifiers adjust the properties of the data types, such as their size or the range of values they
can store. The modifiers include:

• signed: Indicates that a data type can represent both positive and negative values.
• unsigned: Indicates that a data type can only represent non-negative values, allowing a larger
range of positive values.
• long: Increases the size of the data type to store larger values.
• short: Decreases the size of the data type, typically to save memory.
• long can also be applied to the double data type in C++ to increase its precision.

The representation of these data types and their combinations can be machine-specific in C++. This
means that the size and range of these data types can vary depending on the system architecture (e.g.,
a 16-bit or 32-bit machine).

Unit: 2 - Basic Structure of C++ 26


DCA1210: Object-Oriented Programming using C++

Figure 5: C++ Data Types

The datatypes supported in C++ are listed below with size and range:

Table 3: Basic Datatypes in C++


Data Type Size (in bytes) Values that can be taken
Signed int 2 -32768 to 32767
unsigned int 2 0
Signed Char 1 -128 to 127
unsigned char 1 0 to 255
Float 4 3.4
Double 8 1.7
long double 10 3.4
long int 4 -2147483648 to 2147483647
short int 2 -31768 to 32767

8.2. Variables
Variable is a container of data i.e. Variables are names used to refer to some memory location.
Variables can be named according to the following rules:

• Variable name must begin with a letter.


• Variable name contains letters, numbers and underscore.

Unit: 2 - Basic Structure of C++ 27


DCA1210: Object-Oriented Programming using C++

• Variable names are case sensitive.


• Reserve words of C++ cannot be used

Declaration and definition of variables:


Variables have to be declared before being used in the program. Variable declaration tells the
compiler the name and datatype of the concerned variable. General syntax of declaration of variable
is
Datatype variablename;

Example:
int p;

The above declaration declares an integer variable named p. you can declare multiple variables of the
same type in a single statement by separating them with commas. The Datatype of a variable
optionally initializes the variable to a specific value. Values can be assigned to the variable during
declarations, or can be initialized separately using the assignment operator equal (=).

Example:
Int P=4, Q=8
Or
Int P, Q
P=4, Q=8

8.3. Token of C++: Identifiers, Keywords, Constants, Operators


A programmer uses C++ tokens to write a program. C++ supports the following types of tokens:
identifiers, keywords, constants and operators.

8.3.1. Identifiers
Identifiers are used to define a name. They are mostly used to name variables (ex: array, structure),
functions, class etc. Every language uses its own rules for naming the identifiers. In C++, identifiers
can be named according to the following rules:

• Only alphabets, digits, characters and underscores are permitted.


• A name cannot start with a digit.
• An identifier cannot start with a symbol.
• Keywords cannot be used as an identifier.

Unit: 2 - Basic Structure of C++ 28


DCA1210: Object-Oriented Programming using C++

Some examples for valid identifiers are:


Name, first_name, last_name

8.3.2. Keywords
Keywords are also known as ‘reserve words’. Many keywords are common to C as well C++. All
Keywords have a specific meaning and purpose. Some of the C++ keywords are: auto, break, catch,
class, delete, do, for, new, int, long, mutual, public, protected, return, size of, signed, void, while.

8.3.3. Constants
The constants in C++ can be a numeric, a character or string constants. The value of a constant does
not change during the program. You should initialize a constant value when you create it. Example:
const int data=10;

Here ‘const’ allows you to create constants. The value of data is fixed during the entire program.

8.3.4. Operators
Operators are symbols used to perform operations on variables and values.

Examples include:
• Arithmetic operators: + (plus), - (minus), * (asterisk for multiplication), / (slash for division).
• Relational operators: == (equal to), != (not equal to).
• Assignment operator: = (equals).

For instance, in the statement int num = 10 + 5;


int is a keyword,
num is an identifier,
10 and 5 are constants,
= (equals) is the assignment operator,
+ (plus) is the arithmetic operator.

Unit: 2 - Basic Structure of C++ 29


DCA1210: Object-Oriented Programming using C++

9. SUMMARY
Let us recapitulate the important points discussed in this unit:

• Computer performs a variety of tasks with the help of programming languages. In 1980, Bjarne
Stroustrup, from Bell labs, began the development of the C++ language.

• C++ is a superset of C. Several features are similar in C and C++. Object-oriented Programming
(OOP) is considered as important as the development of high level languages. The basic features
of OOP language are: Objects, Classes, Inheritance. Polymorphism, Encapsulation.

• Object-oriented Programming enables storing of data and functions together, which in turn
enables hiding of data from unnecessary exposure.

• A class defines the characteristics of its objects and the methods that can be applied to its objects.
The main advantage of Inheritance is "code reusability".

• C++ language supports following data types: char, int, float, double. A programmer uses C++
tokens to write a program.

• C++ supports the following types of tokens: identifiers, keywords, constants and operators. An
expression is a sequence of operators and operands, used for computation.

• The header file “iostream.h” defines the cin, cout, objects, which correspond to the standard input
stream and the standard output stream respectively.

• To write and execute C++ programs, you need to have a text editor and C++ compiler. In market
various types of compilers are available: GNU C++, Borland C++, Zortech C++, NDP C++, etc.

Unit: 2 - Basic Structure of C++ 30


DCA1210: Object-Oriented Programming using C++

10. SELF-ASSESSMENT QUESTIONS


Multiple choice Questions
1 What is the correct file extension for a C++ source file?
a) .cp
b) .cpp
c) .cpl
d) .cxp
2 Which of the following is a basic feature of a C++ program?
a) Classes
b) Data Structures
c) Modules
d) Pointers
3 What is the correct syntax for a single-line comment in C++?
a) # This is a comment
b) /* This is a comment */
c) // This is a comment
d) ** This is a comment **
4 Which operator is used to output data to the screen in C++?
a) <<
b) >>
c) ==
d) //
5 Which of the following libraries is typically included at the beginning of a C++ program to
handle input and output?
a) <iostream>
b) <math.h>
c) <string>
d) <stdio.h>
6 What does the namespace std stand for in C++?
a) Standard

Unit: 2 - Basic Structure of C++ 31


DCA1210: Object-Oriented Programming using C++

b) String Data
c) Structured Data
d) Static Data
7 What is the default return type of the main function in C++?
a) void
b) int
c) char
d) float
8 Which of the following is NOT a valid C++ data type?
a) int
b) double
c) string
d) char
9 Which section of a C++ program contains the declarations of the classes?
a) Header files
b) Implementation files
c) Main function
d) Preprocessor directives
10 Which command is used to compile a C++ program in UNIX?
a) cc
b) compile
c) CC
d) g++
11 Which of the following is a basic component of a C++ program?
a) Identifiers
b) Flowcharts
c) Spreadsheets
d) Reports
12 What does the return 0; statement signify in the main() function?
a) End of the program with an error
b) End of the program with successful execution

Unit: 2 - Basic Structure of C++ 32


DCA1210: Object-Oriented Programming using C++

c) Start of the program


d) Continuation of the program
True or False:

13 The cin object is used for output in C++.

14 In C++, you can have multiple classes within a single program.

Fill in the Blanks:

15 The ________ modifier increases the size of an integer type in C++.

Unit: 2 - Basic Structure of C++ 33


DCA1210: Object-Oriented Programming using C++

11. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective

A collection of functions and classes written in the C++ programming


C++ Program - language, typically including one or more source files, header files, and a
main function for execution.

A header file in C++ (#include <iostream>) that provides the basic


Iostream File -
input/output stream functionality, including cin and cout.

A declarative region in C++ that provides a scope to the identifiers (names


Namespace -
of types, functions, variables, etc.) inside it, preventing naming conflicts.

Named storage locations in memory that hold data values during the
Variables -
execution of a program, with types such as int, float, and char.

The operator >> used in C++ for reading input from the user, typically
Input Operator -
with cin.

Cascading of I/O A technique in C++ where multiple I/O operations are combined in a
-
Operators single statement using the << or >> operators.

A blueprint in C++ for creating objects, encapsulating data for the object
Class -
and methods to manipulate that data.

An instance of a class in C++ that contains data and functions defined by


Object -
its class.

A file containing the source code of a C++ program, typically with a .cpp
Source File -
extension, that needs to be compiled.

The process of translating source code written in C++ into machine code
Compiling
that can be executed by the computer.

The process of combining object files and libraries into a single executable
Linking
program.

The classification of data items, such as integers, floating-point numbers,


Data Types and characters, determining the type of data that can be stored in a
variable.

Unit: 2 - Basic Structure of C++ 34


DCA1210: Object-Oriented Programming using C++

Fundamental Data
Basic data types provided by C++, such as int, char, float, and double.
Types

Keywords in C++ (signed, unsigned, long, short) used to alter the


Modifiers
properties of basic data types to increase their range or precision.

Names used to identify variables, functions, classes, and other user-


Identifiers
defined items in C++.

Reserved words in C++ that have a special meaning and cannot be used
Keywords
as identifiers, such as int, class, return.

Fixed values in C++ that do not change during the execution of a program,
Constants
declared using the const keyword.

Symbols in C++ that perform operations on variables and values, such as


Operators
+, -, *, /, and =.

Preprocessor Instructions in C++ that are processed by the preprocessor before the
Directive actual compilation starts, such as #include and #define.

A file with a .h extension in C++ that typically contains function


Header File
prototypes, class declarations, and macro definitions.

The concept in OOP of bundling the data and the methods that operate on
Encapsulation -
the data within a single unit, a class.

A feature in OOP that allows a new class to inherit properties and


Inheritance -
behaviors (methods) from an existing class.

The ability in OOP to process objects differently depending on their data


Polymorphism - type or class, typically achieved through method overloading or
inheritance.

The smallest unit in a C++ program, which includes keywords, identifiers,


Token -
constants, operators, and punctuation marks.

Unit: 2 - Basic Structure of C++ 35


DCA1210: Object-Oriented Programming using C++

12. TERMINAL QUESTIONS


1. What are the comments in C++? Discuss the different types of comments used in C++ with
examples.
2. Describe the role and significance of the iostream file in C++.
3. Define and explain the concept of namespaces in C++. Why are they important?
4. Discuss the different return types that can be used in the main() function in C++.
5. Explain the use of input and output operators in C++ with examples.
6. Describe the process of creating a source file in C++. What file extensions are typically used?
7. Explain the purpose and use of cascading I/O operators in C++. Provide an example.
8. What is the significance of using data types in C++? Explain with examples.
9. Write a short note on structure of C++ program.
10. Provide a detailed explanation of the process of creating, compiling, and linking a C++ program in
different environments

Unit: 2 - Basic Structure of C++ 36


DCA1210: Object-Oriented Programming using C++

13. ANSWERS
Self-Assessment Questions
1. .cpp
2. Classes
3. // This is a comment
4. <<
5. <iostream>
6. Standard
7. Int
8. String
9. Header files
10. CC
11. Identifiers
12. End of the program with successful execution
13. False
14. True
15. long

Terminal Questions Answers


1. Refer to 2.2 section
2. Refer to 2.2 section
3. Refer to 2.2 section
4. Refer to 2.2 section
5. Refer to 2.2 section
6. Refer to 2.6 section
7. Refer to 2.3 section
8. Refer to 2.8 section
9. Refer to 2.5 section
10. Refer to 2.7 section

Unit: 2 - Basic Structure of C++ 37


DCA1210: Object-Oriented Programming using C++

14. REFERENCES
1. E Balagurusamy, “Object-Oriented Programming with C++”, 8th edition, 2020, Tata McGraw Hill
Publications.
2. Object-Oriented Programming Using C++, By B. Chandra, CRC Press.
3. Starting Out with C++: From Control Structures Through Objects, Global Edition, by Tony Gaddis,
Pearson Education.

Unit: 2 - Basic Structure of C++ 38


DCA1210: Object-Oriented Programming using C++

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 2

DCA1210
OBJECT - ORIENTED PROGRAMMING
USING
Unit: 3 - Operators and Program Structure in C++ C++ 1
DCA1210: Object-Oriented Programming using C++

Unit – 3
Operators and Program Structure in
C++

Unit: 3 - Operators and Program Structure in C++ 2


DCA1210: Object-Oriented Programming using C++

TABLE OF CONTENTS

Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4-5
1.1 Objectives - -
2 Operators - -

2.1 Operators: expressions i, ii, iii, iv - 6 - 18

2.2 New Operators v, 1 -


3 C++ Program Structure - - 19 - 20
4 Compiling and Executing C++ Program 2 -
21 - 33
4.1 Conditional control statements 3, 4 -
5 Summary - - 34
6 Self-Assessment Questions - 1 35 - 36
7 Glossary - - 37 - 38
8 Terminal Questions - - 39
9 Answers - - 40
10 References - - 41

Unit: 3 - Operators and Program Structure in C++ 3


DCA1210: Object-Oriented Programming using C++

1. INTRODUCTION
In the previous unit 2, learners have gained a foundational understanding of C++ programming,
covering the basic structure of a C++ program, key features, and the use of comments and output
statements. They explored essential components like variables, data types, and the input/output
operators, while also delving into namespaces, the return type of the main() function, and also they
learned about tokens such as identifiers, keywords, constants, and operators, and saw practical
applications through sample programs and the creation of source files.

In this unit, learners will study the foundational aspects of operators and their applications in C++
programming. The unit begins with an exploration of various operators and expressions, providing
insight into how they are used to perform different operations within a program. Learners will
explore into new operators introduced in C++, including the scope resolution operator, which allows
access to global variables and specific class members, member dereferencing operators that facilitate
pointer operations within classes, and memory management operators that streamline dynamic
memory allocation and deallocation. Learners also learn manipulators, which are essential for
formatting output in C++ and the structure of a typical C++ program, highlighting the importance of
each component from preprocessor directives to the main function. Learners will gain practical
knowledge on how to compile and execute C++ programs, ensuring they understand the complete
workflow from writing code to running it successfully. Learners will also learn conditional control
statements, to make decisions within their programs based on various conditions.

To study this unit, learners should start by writing and running small code snippets to understand
the different operators in C++. Practice structuring simple programs to see how the components fit
together. They should be familiar with the compilation process by using different tools and
troubleshooting errors. Finally, write programs that use conditional control statements, and think
through the logic with flowcharts or pseudocode before coding.

Unit: 3 - Operators and Program Structure in C++ 4


DCA1210: Object-Oriented Programming using C++

1.1. Objectives
After studying this unit, you should be able to:
• Explain the purpose and use of different operators in C++ programming.
• Explain the role of the scope resolution operator in
accessing global variables and class members.
• Explain the purpose of memory management
operators (new, delete) in dynamic memory
allocation.
• Describe the function of manipulators like endl and
setw in formatting output.
• Analyse the output of a compiled C++ program to
verify its correctness.
• Explain the function of conditional control statements (if, else, switch) in C++.

Unit: 3 - Operators and Program Structure in C++ 5


DCA1210: Object-Oriented Programming using C++

2. OPERATORS
Operators are fundamental components of any programming language, and C++ offers a rich set of
them to perform various operations on data. An operator in C++ is a symbol that tells the compiler to
perform specific mathematical, logical, or bitwise operations. These operators act on operands, which
are the variables or values on which the operations are performed. C++ has a rich set of operators.
C++ supports all C operators. In C++, operators are used to perform a specific operation on a set of
operands in an expression.

Operators supported in C++ are listed below.


1. Arithmetic operators (+,-, *,/, %, ++,- -)
2. Relational operators (>,<, >=, <=, ==, !=)
3. Logical Operators (&&, ||, !)
4. Bit-wise operators (&, |. ^, ~ )

Some of the notable new operators in C++ include:


• the scope resolution operator (::), which allows access to global variables or members of a
class, and
• the memory management operators ‘new and delete’, which are used to allocate and deallocate
memory dynamically.

There are also operators specifically for handling pointers to members of a class and for managing
formatted output, like the insertion (<<) and extraction (>>) operators.

There are a few other operators supported by C++ language: sizeof, the conditional operator and the
cast operator.

2.1. Operators: expressions


An expression is a sequence of operators and operands, used for computation. Expression evaluation
may produce a result (example: evaluation of 2+2 produces the result 4).

i. Arithmetic operators: C++ provides five simple arithmetic operators for creating arithmetic
expressions. Table 1.1 below illustrates these arithmetic operators with example. If the value of
X=6 and Y=3, results for the arithmetic operations are shown in Table 1.1.

Unit: 3 - Operators and Program Structure in C++ 6


DCA1210: Object-Oriented Programming using C++

Table 1: Arithmetic operators in C++


Operator Description Example
+ Used to add two operands X+Y will give result 9
- Used to subtract second operand from the first X-Y will give result 3
* Used to multiply both operands X *Y will give result 18
/ Used to perform division operation X/ Y will give result 2
% Module operator, it gives reminder of integer Division X%Y will give result 0
++ Increment operator, increase integer value by one X++ will give value 7
-- Decrement operator, decreases integer value by one X- - will give value 5

ii. Relational operators:


Relational operators are binary operators. Relational operators test data values against one other,
and return the value as either 1 (true) or 0 (false).

The Table 1.2 illustrates relational operators with example. In example consider X=10 and Y=20.

Table 2: Relational operators in C++

Operator Description Example


Verifies whether the value of the left operand is greater than the (X>Y) is not
>
value of the right operand; if yes, then the condition become true. true
Verifies whether the value of the left operand is less than the value
< (X<Y )is true
of the right operand; if yes, then the condition becomes true.
Verifies whether the value of the left operand is greater than or
(X>=Y) is
>= equal to the value of the right operand; if yes, then the condition
not true
result is true.
Verifies whether the value of the left operand is less than or equal to
(X<=Y) is
<= the value of the right operand; if yes, then the condition result is
not true
true.
Verifies whether the values of two operands are equal or not; if (X==Y) is
==
equal, then condition result is true. not true
Verifies whether the values of two operands are equal or not; if not (X!=Y) is
!=
equal, then condition result is true. true
iii. Logical Operators:
Logical operators are used to combine multiple conditions, or to compare Boolean expressions.
The Table 1.3 illustrates logical operators with example. In the example given below, assume that
variable X holds binary one (1) and variable Y holds binary zero (0).

Unit: 3 - Operators and Program Structure in C++ 7


DCA1210: Object-Oriented Programming using C++

Table 3: Logical operators in C++

Operator Description Example


(X && Y)
Logical AND operator. If both the operands are non-zero, then
&& Result is
condition becomes true.
False
(X || Y)
Logical OR operator. If any of the two operands are non-zero, then
|| Result is
the condition becomes true.
True
Logical NOT operator: used to reverse the logical states i.e. If the
(! X) Result is
! condition is true, then logical NOT operator will make it false. If the
False
condition is false, then logical NOT operator will make it true.
iv. Bitwise operators:
Bitwise operators modify variables considering the bit patterns that represent the values.

Bitwise AND (&) and bitwise OR (|) work similarly to their logical AND and logical OR counterparts.
However, rather than evaluating a single boolean value, they are applied to each bit. Of all the
bitwise operators, the bitwise NOT operator (~) is perhaps the easiest to understand. It simply
flips each bit from a 0 to a 1, or vice versa. Bitwise exclusive-or (^) performs the exclusive-or
operation on each pair of bits. Exclusive-or is commonly abbreviated as XOR. The exclusive-or
operation takes two inputs and returns a 1 if either of the inputs is a 1, but not if both are. That is,
if both inputs are 1 or both inputs are 0, it returns 0.

The Table 1.4 illustrates Bitwise logical operators with example. Let us assume that variable X
holds binary value 5 (101) and variable Y holds binary 6 (110), then the result in the example
column would be as given in table 1.4.

Table 4: Bitwise logical operators in c++

Operator Description Example


When evaluating bitwise AND, if all bits in a column are 1, the (X&Y) Result
&
result for that column is 1. is 100
When evaluating bitwise OR, if any bit in a column is 1, the result (X|Y) Result is
|
for that column is 1. 111
When evaluating bitwise XOR, if there is an odd number of 1 bits (X^Y) Result is
^
in a column, the result for that column is 1. 011
When evaluating bitwise NOT, it toggles each bit from 0 to a 1, or (~ X) Result is
~
vice versa 010

Unit: 3 - Operators and Program Structure in C++ 8


DCA1210: Object-Oriented Programming using C++

2.2. New Operators:


The new operators are:
• :: - Scope resolution operator
• ::* - Pointer-to-member declarator
• ->* - Pointer-to-member operator
• .* - Pointer-to-member operator
• delete - Memory release operator
• endl - Line feed operator
• new - Memory allocation operator
• setw - Field width operator

i. Scope Resolution Operator:


• Similar to C, C++ is a block-structured language. This means that the code is divided into blocks,
and variables declared within a block are local to that block.
• The same variable name can be used in different blocks, but each instance of the variable will have
a different scope and will be treated as a separate entity. This is known as variable scoping.
• The scope of a variable extends from the point where it is declared to the end of the block in which
it is declared. Any reference to the variable within that block will use the value assigned to it within
that scope.

Example:
………..
………..
{
Int x=10;
………..
………..
}
…………
…………
{
Int x=1;
……….

Unit: 3 - Operators and Program Structure in C++ 9


DCA1210: Object-Oriented Programming using C++

……….
}

The two x variables declared in different blocks refer to distinct memory locations with different
values. Statements in the second block cannot access the x variable from the first block, and vice versa.
In C++, blocks are frequently nested.

For example, in the above code int x = 10; is declared in a block, and later in another block (within or
outside) int x = 1; is declared, these two x variables are treated as distinct variables with separate
memory locations.

For instance, the following structure is common.

Figure 1: Concept of block nesting in C++

The figure 1 illustrates the concept of block nesting in C++. Here, you see two blocks, Block 1 and
Block 2.

• Block 1 contains a declaration of an integer variable x with the value 10.


• Block 2 is nested within Block 1 and also declares an integer variable x but assigns it the value 1.

This nesting shows that each block has its own scope, and the variable x in Block 2 is separate from
the variable x in Block 1, despite having the same name. When the variable x is accessed within Block
2, it refers to the value 1 because that is the value assigned within its local scope. Meanwhile, x in
Block 1 refers to the value 10. The inner declaration in Block 2 hides the outer declaration in Block 1
within its scope, demonstrating the concept of variable shadowing in nested blocks (i.e., if int x = 1; is
declared inside another block where int x = 10; already exists, within the inner block, x will refer to 1,
not 10.)

Unit: 3 - Operators and Program Structure in C++ 10


DCA1210: Object-Oriented Programming using C++

C++ resolves the issue of accessing a global variable when an inner block declares a variable with the
same name. In C, if a variable is declared in an inner block, it hides any global variable with the same
name, making the global version inaccessible within that block.

C++ introduces a solution to this problem with the scope resolution operator (::). This operator
allows you to access the global version of a variable, even when there is a local variable with the same
name in the current block.

The syntax for using the scope resolution operator is:

:: variable-name

Program on Scope Resolution Operator

#include <iostream>
using namespace std;
int m = 10; // global m

int main()
{
int m = 20; // m redeclared, local to main

{
int k = m; // m declared again, local to inner block
int m = 30; // local to inner block

cout << "We are in inner block \n";


cout << "k = " << k << "\n";
cout << "m = " << m << "\n";
cout << "::m = " << ::m << "\n";
}

cout << "\nWe are in outer block \n";


cout << "m = " << m << "\n";
cout << "::m = " << ::m << "\n";

return 0;
}

Unit: 3 - Operators and Program Structure in C++ 11


DCA1210: Object-Oriented Programming using C++

Output:
We are in inner block
k = 20
m = 30
::m = 10

We are in outer block


m = 20
::m = 10

The above C++ code demonstrates the concept of variable scope and the use of the scope resolution
operator (::) to distinguish between global and local variables with the same name. The program
begins by declaring a global variable m initialized with the value 10. Within the main() function,
another variable m is declared and initialized with the value 20, which is local to the main() function
and thus hides the global m within this scope.

Inside the main() function, there is an inner block that further declares a new variable m with the
value 30, local only to this inner block. In this block, another variable k is initialized with the value of
the m from the main() function (which is 20). The program then uses cout statements to print the
values of k, the local m (30), and the global m (10) using the scope resolution operator ::m.

After the inner block, the program returns to the scope of the main() function, where it prints the
value of the local m (20) and again accesses the global m (10) using the scope resolution operator.

A major application of the scope resolution operator is in the classes to identify the class to which a
member function belongs.

ii. Member Dereferencing Operators


• C++ allows us to define classes that contain various types of data and functions as members.
• C++ also permits accessing these class members through pointers. To facilitate this, C++ provides
a set of three pointer-to-member operators.
• The operators mentioned in table 1.5 are important for accessing members of a class when using
pointers.

Table 5: Member dereferencing Operator


Operator Function
::* To declare a pointer to a member of a class

Unit: 3 - Operators and Program Structure in C++ 12


DCA1210: Object-Oriented Programming using C++

* To access a member using the object name


and a pointer to that member
->* To access a member using a pointer to the
object and a pointer to that member

iii. Memory Management Operators


• In C, memory is dynamically allocated at runtime using the functions malloc() and calloc().
• To free dynamically allocated memory, the free() function is used.
• These dynamic allocation techniques are employed when the required memory size isn't known
in advance.
• Although C++ supports the C-style memory management functions, it also introduces two unary
operators: new and delete.
• These operators provide a more efficient and easier way to allocate and free memory,
manipulating memory on what is referred to as the free store.
• new is used to create (allocate) memory for objects dynamically.
• delete is used to destroy (free) the memory allocated by new.
• An object created using new remains in existence until it is explicitly destroyed using delete,
regardless of the block structure in the program.
• The lifetime of such objects is directly controlled by the programmer, independent of the scope in
which they were created. This allows objects to persist beyond the scope in which they were
allocated, providing greater flexibility in managing memory.

The new operator is used to create objects of any given type, following the general syntax:

pointer-variable = new data-type;

In this syntax, pointer-variable is a pointer of the specified data-type. The new operator allocates
enough memory to hold a data object of the specified data-type and then returns the address of this
allocated memory. The data-type can be any valid data type in C++. The pointer-variable stores the
address of the allocated memory.

Example:
int *p= new int;
Float *q= new float;
Subsequently, the statements
*p = 10;

Unit: 3 - Operators and Program Structure in C++ 13


DCA1210: Object-Oriented Programming using C++

*q= 8.5;

Assign 10 to the newly created int object and 8.5 to the float object.

The new operator in C++ can also be used to initialize memory at the time of allocation. The syntax
for this operation is:

pointer-variable = new data-type (value);

where, Size refers to the number of elements in the array.

Example: Int *p=new int [15] // Creates a memory space for an array of 15 integers, where p[0] will
refer to first element and p[14] refers to last element.

When creating multi-dimensional arrays with new, all the array sizes must be given.
array_ptr = new int[3][5][4]; // legal
array_ptr = new int[m][5][4]; // legal
array_ptr = new int[3][5][ ]; // illegal
array_ptr = new int[ ][5][4]; // illegal

When a data object becomes unnecessary, it is eliminated to free up the memory space for future use.

The general form of its use is:

delete pointer-
variable;

A pointer-variable is a pointer that references a data object created with the new keyword.

Example:
delete p;
delete q;

To deallocate a dynamically allocated array, we must use the following syntax of the delete operator:

delete [size] pointer-


variable;

The size parameter indicates the quantity of elements in the array that will be released. An issue with
this approach is that the programmer must recall the size of the array. In modern iterations of C++, it
is unnecessary to explicitly specify the size.

Example: delete [ ]p; // deletes the entire array pointed to by ‘p’.

Unit: 3 - Operators and Program Structure in C++ 14


DCA1210: Object-Oriented Programming using C++

If there is not enough memory available for allocation, the program will encounter a memory shortage
and may not be able to perform the desired tasks. When using functions like malloc(), the new
operator will yield a null pointer. Hence, it would be advisable to verify the pointer generated by the
'new' operator before to its utilisation.

The procedure is carried out in the following manner:


……..
……..
p = new int;
if(!p)
{
cout << "allocation failed \n";
}
………
………

The new operator has several advantages compared to the procedure malloc():
• It automatically calculates the dimensions of the data object. There is no necessity for us to utilise
the sizeof operator.
• The right pointer type is automatically returned, eliminating the need for a type cast.
• It is feasible to instantiate the object during the allocation of memory.
• New and delete, like every other operator, have the ability to be overloaded.

iv. Manipulators
Manipulators are operators used for the purpose of formatting the display of data. The two most often
used manipulators are endl and setw.

The usage of the endl manipulator in an output statement results in the insertion of a linefeed. It
produces an identical outcome to use the newline character \n.

For example, the statement


………
………
cout << "m = " << m << endl;
cout << "n = " << n << endl;
cout << "p = " << p << endl;

Unit: 3 - Operators and Program Structure in C++ 15


DCA1210: Object-Oriented Programming using C++

………
………

would cause three lines of output, one for each variable. If we assume the values of the variables as
2597, 14, and 175 respectively, the output will appear as shown below:

m = 2597
n= 14
p = 175

Here, the numbers are right justified. In order to get this type of output, it is necessary to define a
uniform field width for all the numbers and ensure that they are written in a right-justified manner.
The setw manipulator performs this task.

It is represented as:
Cout << setw(5) << sum << endl;

The setw(5) manipulator is used to set a field width of 5 for displaying the value of the variable sum.
The value is aligned to the right within the field.

3 4 5

Example to illustrate endl and setw:


#include <iostream>
#include <iomanip> // for setw

using namespace std;

int main()
{
int Basic = 950, Allowance = 95, Total = 1045;

cout << setw(10) << "Basic" << setw(10) << Basic << endl
<< setw(10) << "Allowance" << setw(10) << Allowance << endl
<< setw(10) << "Total" << setw(10) << Total << endl;

return 0;
}

Output:
Basic 950

Unit: 3 - Operators and Program Structure in C++ 16


DCA1210: Object-Oriented Programming using C++

Allowance 95
Total 1045

The above C++ program demonstrates how to use the setw and endl manipulators to format the
output of a simple program. The program begins by including the necessary headers: #include
<iostream> for input/output stream objects and #include <iomanip> for formatting manipulators
like setw. It then uses the using namespace std; directive to allow access to standard library elements
without the need for prefixing them with std::.

In the main function, three integer variables, Basic, Allowance, and Total, are declared and assigned
the values 950, 95, and 1045, respectively. The program then uses a series of cout statements to print
these variable names and their corresponding values in a tabular format. The setw(10) manipulator
is employed to set the width of the output field to 10 spaces, ensuring that each label and its
corresponding value are right-aligned in their respective fields. The endl manipulator is used to insert
a newline character, moving the output to the next line and flushing the output buffer.

As a result, the output is neatly formatted, with each label ("Basic", "Allowance", "Total") aligned with
its corresponding value in a structured, easy-to-read format.

The idea of object-oriented programming gained momentum in the 1970s and in the early 1980s.
Bjorn Stroustrup integrated the object-oriented programming into the C language. C++ is a superset
of C. Several features are similar in C and C++. At this time, many new features like object,
class,inheritance, virtual functions and function overloading were added. Therefore, there is a ‘++’
symbol in C++. The ++ operator in the C++ means many new features were added around this time.
The most notable features are - object, class, inheritance, virtual functions and function overloading.

Limitations of procedural languages:


Procedural languages focused on organizing program statements into procedures or functions. Larger
programs were either broken into functions or modules which had defined purpose and interface to
other functions.

Procedural approach for programming had several problems as the size of the software grew larger
and larger. One of the main problems was that of the data being completely forgotten. The emphasis
was on the action and the data was only used in the entire process. Data in the program was created
by variables, and if more than one function had to access data, then global variables were used. The
concept of global variables itself is a problem as it may be accidentally modified by an undesired

Unit: 3 - Operators and Program Structure in C++ 17


DCA1210: Object-Oriented Programming using C++

function. This also leads to difficulty in debugging and modifying the program when several functions
access a particular data.

The object Oriented approach overcomes this problem by modeling data and functions together,
thereby allowing only certain functions to access the required data.

The procedural languages had limitations of extensibility as there was limited support for creating
user-defined data types and defining how these datatypes are to be handled. For example, it would
be difficult if the programmer had to define his own version of string, and define how this new
datatypes will be manipulated. The Object Oriented Programming provides this flexibility through the
concept of class.

Another limitation of the procedural languages is that the program model is not closer to real world
objects. For example, if you want to develop a gaming application of car race, what data you would
use and what functions you would require are difficult questions to answer in the procedural
approach. The object oriented approach solves this further by conceptualizing the problem as group
of objects which have their own specific data and functionality. In the car game, for example we would
create several objects such as player, car, and traffic signal and so on.

Some of the languages that use object oriented programming approach are C++, Java, Csharp,
Smalltalk etc. We will be learning C++ in this Self Learning Material (SLM) to understand the object
oriented programming.

Unit: 3 - Operators and Program Structure in C++ 18


DCA1210: Object-Oriented Programming using C++

3. C++ PROGRAM STRUCTURE


The structure of a C++ program is designed to organize code logically, starting from preprocessor
directives, through function and class definitions, to the main() function where program execution
begins. Each part of the structure serves a specific purpose, contributing to the overall clarity and
functionality of the program.

i. Preprocessor Directives
• Preprocessor directives are lines included at the beginning of a C++ program. They are
instructions to the preprocessor, which is a part of the compilation process.
• Common preprocessor directives include #include and #define.
• #include is used to include standard libraries or user-defined header files that contain
functions or classes used in the program.

ii. Namespace Declaration


• The using namespace std; directive is often used to avoid prefixing standard library names
with std::.
• This is optional but common in C++ programs.

iii. Global Variable Declaration (Optional)


• Variables that need to be accessed by multiple functions can be declared globally, outside of
all functions, usually after the preprocessor directives.

Example:
int globalVar = 0;

iv. Function Prototypes (Optional)


• Function prototypes provide the compiler with information about a function that is defined
later in the program. They are optional but useful in organizing code.

Example:
void myFunction(int, double);

v. Main Function
• The main() function is the entry point of a C++ program. Every C++ program must have one
and only one main() function.

Unit: 3 - Operators and Program Structure in C++ 19


DCA1210: Object-Oriented Programming using C++

• This function can return an integer (int) to the operating system, indicating the success or
failure of the program

Example:
int main() {
// Code to be executed
return 0;
}

vi. Function Definitions


• Functions can be defined after the main() function or even in separate files.
• Functions encapsulate specific tasks, making the program modular and easier to manage.

vii. Classes (Optional)


• Classes define new data types that encapsulate data and functions that operate on the data.
Classes are fundamental in object-oriented programming in C++.

Example:
class MyClass {
public:
int myNumber;
void myFunction() {
// Code to be executed
}
};

viii. Statements and Expressions


• Within functions, including main(), you write statements and expressions that define the
actual logic of the program.

ix. Comments
• Comments are used to explain the code and are ignored by the compiler.
• They can be single-line (//) or multi-line (/* */).

x. Return Statement
• The main() function usually ends with a return 0; statement, which indicates that the program
has ended successfully.

Unit: 3 - Operators and Program Structure in C++ 20


DCA1210: Object-Oriented Programming using C++

4. COMPILING AND EXECUTING C++ PROGRAM


There are three stages in executing a C++ program. They are: Compiling, Linking and Running the
program.

Compiling:
Compiling is a process of converting source code to machine code. Each .cpp file is a program file
which is also known as source file, and when it is compiled, you get an object file with extension .obj.

The c++ programs have to be typed in computer. Your program file is saved with an extension .cpp.
This is known as ‘source code’. The C++ compiler takes source code as its input and if there are no
errors, it produces a machine code of your program, which is saved in a disk file with the same name,
but with extension .obj. Compilation process translates program file in to object file, which is a
machine-readable code.

C++ programs can be implemented on different Operating systems (ex: Windows, UNIX, DOS, etc.). In
market, various types of compilers are available. Some of them are: GNU C++, Borland C++, Zortech
C++, NDP C++, etc.

Linking:
Linking is an essential process when executing the program. The role of a linker is to link the files and
functions required and used by programs. The object codes of these programs and the library files
are linked to create a single executable file. For example, if the programmer uses clrscr (), then the
object code of the function should be brought from “conio.h” header file. When the linking process is
completed, the program code generates executable file.

Running the program:


Third and the last stage is running the executable file, where the statements in the program will be
executed one by one.

Fig. 1.2 shows the entire process. When you execute the program, the compiler displays the output
of the program and comes back to the program editor. To view the output, wait for the user to press
any key to return to the editor and type getch() as the last statement in the program. Getch() is an
inbuilt predefined library function which inputs a character from the user through standard input.
However, you should include another header file named conio.h to use this function. Conio.h contains
the necessary declarations for using this function. The include statement will be similar to iostream.h.

Unit: 3 - Operators and Program Structure in C++ 21


DCA1210: Object-Oriented Programming using C++

Figure 2: Execution process of C++ program

During compilation, if there are any errors, they will be listed by the compiler.

The errors may be any one of the following:

1. Syntax error
Syntax error is an error in the structure or spelling of a statement. It occurs when the program
code breaks the basic syntax rules of C++ statement, as, for instance, in the wrong use of reserved
words, improper variable names, variables without declaration etc. Further examples of syntax
errors are- missing semi colon or parenthesis, type integer for int datatype etc. Often,

approximate location of error; and the statement number is displayed to help the programmer.
You can see the statement, make correction/s to the program file, save and recompile it.

2. Logical error
This error occurs due to some flaw in the logic. Logical error occurs when you use a statement
that is syntactically correct, but doesn’t do what you need. The compiler doesn't identify when any
logical error happens in the program. When compared to syntax error, finding a logical error is
time-consuming for the programmer. However, it can be traced using the debug tool in the editor.

3. Linker error
Linker error occurs when the files go missing during linking. Linker error implies that the linker
is unable to build an executable program from the object code you provided. The following can be
an example for a linker error-supposing you have used a function print, if the linker cannot find
the function in any libraries that you have declared, then it is a linker error.

Unit: 3 - Operators and Program Structure in C++ 22


DCA1210: Object-Oriented Programming using C++

4. Runtime error
Runtime error occurs during the execution of a program. If the program performs invalid
operation during execution of the program, then runtime errors are detected (ex: division by zero,
accessing a null pointer etc.)

Control Statements
There are basically two types of control statements in C++ which allow the programmer to modify
the regular sequential execution of statements. They are- conditional and unconditional control
statements.

4.1. Conditional control statements


The conditional control statements allow the user to choose a set of statements for execution,
depending on a condition. If statement and switch statements are the examples of conditional controls
statements which executes based on the given condition. One more conditional control statement is
the conditional operator. Now let us discuss the three conditional control statements one by one.

If, nested If statements


‘if statement’ is the simple conditional control statement. It controls the sequential flow of executable
statements based on certain conditions.

‘if’ is the keyword used to specify the condition. ‘if’ statement is followed by executable statements
that are enclosed in the curly braces. Curly braces are optional in case of single executable statement

The syntax of if statement is given as:

Syntax:
if (expression or condition)
{
Statement1;
Statement 2;
}

The expression or if condition inside the brackets returns the Boolean value, i.e. true or false. If the
condition or expression is true, then execution will continue through statement1 and statement 2. If
the condition is false, then the program will skip both the statements (i.e. statement1 and statement2).

Unit: 3 - Operators and Program Structure in C++ 23


DCA1210: Object-Oriented Programming using C++

If –else statement;
Another type of if statement is if-else statement. it is useful to execute series of statements. If the
condition is true, then it executes if block statements. If the condition is false then it executes else
block statements.

Syntax:
if (expression or condition)
{
Statement (s)
}
else
{
Statement (s);
}

The example program given below accepts a number from the user, and displays whether given
number is even or odd number.

include <iostream. h>


void main()
{
int x;
cout <<"enter the value of x\n'\"; cin>>x;
if(x%2 == 0)
cout <<" print even number"; else
cout<< " print odd number"; getch();
}

Nested-If statement
If-else statement is useful only if condition has to satisfy two possible alternatives. If there is a need
to check multiple alternatives, then use a nested-if statement, i.e. an “if statement” in an “if statement”
(one if statement having another if statement, and so on is known as ‘nesting’). The syntax of nested-
if statement is specified as:

Syntax:
if (condition1)

Unit: 3 - Operators and Program Structure in C++ 24


DCA1210: Object-Oriented Programming using C++

{
if (condition 2)
{
Statement1;
Statement2;
}
else if (condition3)
{
Statement3;
}
else
Statement 4;
}

Next statements after if statement;

The flowchart for the nested-if statement is shown in figure 3.

Figure 3: Nested- if statement

STUDY NOTE
&& is the AND operator whereas || is the OR operator.

Multiple conditions can be checked using logical && operator (AND) and || operator (OR).

Unit: 3 - Operators and Program Structure in C++ 25


DCA1210: Object-Oriented Programming using C++

For example:
if ((condition1) && (condition2))
statement1;
else
statement2;

In the example given above, statement1 will be executed if both condition1 and condition2 are true.
Otherwise, statement2 will be executed.

if ((condition1 || (condition2))
statement1;
else
statement2;

In the example given above, statement1 will be executed if either condition1 OR condition2 is true,
and even if both are true. Statement2 will be executed if both the conditions are false.

Example: The program below demonstrates the use of nested-if statement.


#include <iostream>
using namespace std;

int main()
{
int studentmarks = 80;

if (studentmarks >= 70) {


cout << "Student passed with A grade" << endl;
}
else {
if (studentmarks >= 50) {
cout << "Student passed with B grade" << endl;
}
else {
if (studentmarks >= 40) {
cout << "Student passed with C grade" << endl;
}

Unit: 3 - Operators and Program Structure in C++ 26


DCA1210: Object-Oriented Programming using C++

else {
cout << "Better luck next time" << endl;
}
}
}
return 0;
}

Output:
Student passed with A grade

The above program number reads student marks, and displays the grade obtained by the student.
Here nested-if conditions are used to check the grade of a student. Once the condition is true, it
displays corresponding message, i.e. the grade of the student.

STUDY NOTE
When using nested loops or blocks, ensure that variable names are unique or use the
scope resolution operator to avoid confusion.

Switch statement
If you are using more if- else statements i.e. nested-if statements in a program, then it looks a bit
confusing. One alternative to nested-if is the switch statement. Switch statement helps you to check
the different values of the same variable and execute the statements accordingly. The syntax of the
switch statement is given below:

Syntax:
switch (variablename)
{
case constant1: statement1;
break;
case constant2: statement2;
break;
case constant3: statement3;
break;
default: statement4;

Unit: 3 - Operators and Program Structure in C++ 27


DCA1210: Object-Oriented Programming using C++

If the variable in the switch statement is equal to constant1 then statement1 is executed, but if it is
equal to constant2 then statement 2 is executed. If it is constant 3, then statement 3 is executed. If the
variable value is not in any of the cases listed, then the default case statement i.e. statement 4 is
executed. The default case specification is optional; however, keeping it is a good practice.

Every case should have a break statement as the last statement. Break statement takes the control
out of the switch statement. Absence of the break statement can cause execution of statements in the
next case. No break is necessary for the last case. In the above syntax, the default case does not contain
a break statement.

The flowchart for the switch statement is shown in Figure 4.

Figure 4: Switch Statement

Example: The following program implements the switch statement


#include <iostream>
using namespace std;

int main() {
char x;
float num1, num2;

Unit: 3 - Operators and Program Structure in C++ 28


DCA1210: Object-Oriented Programming using C++

cout << "Select an operator either + or - or * or / \n";


cin >> x;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch (x) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
break;
case '/':
if (num2 != 0) {
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
} else {
cout << "Division by zero error!" << endl;
}
break;
default:
cout << "Select a valid operator among +, -, *, or /" << endl;
}
return 0;
}

Output:
Select an operator either + or - or * or /
+
Enter two operands: 2 3
2+3=5

Unit: 3 - Operators and Program Structure in C++ 29


DCA1210: Object-Oriented Programming using C++

The example of switch statement given above is used to perform addition or subtraction or
multiplication or division of two numbers. It reads operator values as character, and if the character
value matches with any of the switch case values, then it executes a corresponding operation;
otherwise it displays the default statement message.

Conditional Operator (?)


Conditional operator is also called ‘ternary operator’. The way a Conditional operator works is similar
to that of if-else statements. The general syntax of conditional operator is:

(Condition)? True statement; False statement;

Here ‘?’ is called ‘ternary operator’; if the condition is true, it executes a true statement, otherwise it
executes a false statement.

The statement given below compares two variables and assigns small value to c.
c= (a<b)? a; b;

This can also be rewritten as:


(a<b)? c =a; c=b;

Unconditional control statements


In order to stop the flow of execution unconditionally, C++ supports three types of unconditional
control statements. They are: break, continue and exit statements.

Break, continue and exit statements Break


When a break is encountered inside any conditional block or loop, a conditional block or loop is
terminated, and control passes to the statement outside the conditional block. In the switch statement,
a break statement is used in every case statement to terminate the switch statement, and this passes
the control out of the switch block.

The following program demonstrates the use of break statement.

#include <iostream>
using namespace std;

int main() {
int i = 1, total = 0;
while (i < 10) {
total = total + i;
i++;

Unit: 3 - Operators and Program Structure in C++ 30


DCA1210: Object-Oriented Programming using C++

if (i == 5) {
break;
}
}
cout << "total = " << total << endl;
return 0;
}

Output:
total = 10

In the above program, the user reads two variables, i.e. i=1 and total=0. To find the sum of numbers,
add i value to the total and increment the ‘i’ value by 1(represented with i++). Here, inside an if loop
one more if loop is used. The first if loop checks whether the ‘i' is less than 10 or not. The second if
loop verifies the condition whether i is equal to 5 or not. When i value becomes 5, then it executes the
break statement that will terminate the loop, and then the control passes out of the if block.

Continue statement is used to take the control to the next iteration of the loop. It is used if the control
has to be transferred to the next iteration of the loop based on a condition, skipping all the other
statements in the loop. The following program shows the use of a continue statement.

Example
#include <iostream>
using namespace std;

int main() {
int i = 1, n;
cout << "Enter the number: ";
cin >> n;

while (i <= n) {
if (i % 2 == 0) {
cout << i << " is an even number \n";
}
i++;

Unit: 3 - Operators and Program Structure in C++ 31


DCA1210: Object-Oriented Programming using C++

return 0;
}

Output:
Enter the number: 5
2 is an even number
4 is an even number

The above program enables you to use a continue statement. A Program reads the value of variable n
and displays even number values up to n. There are two if conditions in a program: the first if
condition checks whether i value is less than or equal to n, and the second if condition checks whether
i value is an even number or not. If i value is even, it displays that value, or else the control of execution
is passed to the continue statement. Here the continue statement, first of all, passes the control to if
condition and helps to repeat the loop up to i value equal to n. Once i value becomes greater than n,
then the first if condition becomes false, and the control is passed out of loop.

Exit
Sometimes you need to end your program (or a sub section of a program) earlier than the normal
termination. C++ supports exit statement to exit programs and returns an exit code. Exit is an inbuilt
library function. To use exit program the header file process.h has to be included in the program.

The syntax of an exit program is specified as :

Exit (integer)

Here the integer value return to operating system (OS) while terminating program.

Exit (0) means - no error i.e. successful termination.


Exit (nonzero value) means– error while exiting the program.

#include <iostream>
#include <cstdlib> // for exit()

using namespace std;

int main() {
cout << "Example program for exit" << endl;
exit(0); // This statement terminates the program and returns 0 to the OS
cout << "This statement will never be executed" << endl;

Unit: 3 - Operators and Program Structure in C++ 32


DCA1210: Object-Oriented Programming using C++

return 0;
}

Output:
Example program for exit

The above code demonstrates the use of the exit() function in C++ to terminate a program
immediately. The program begins by including the necessary headers: <iostream> for input/output
operations and <cstdlib> for the exit() function. In the main() function, the program first outputs the
message "Example program for exit" using cout.

The key part of the program is the exit(0); statement, which terminates the program and returns a
status code of 0 to the operating system, indicating successful execution. Once exit(0); is called, the
program stops executing any further code, making any subsequent statements unreachable. For
example, even though there is a cout statement after the exit(0); call, it will never be executed because
the program has already terminated.

This use of exit(0); is helpful in situations where the program needs to be stopped early, possibly due
to an error or a specific condition being met, ensuring that no additional code is run after the
termination point.

Unit: 3 - Operators and Program Structure in C++ 33


DCA1210: Object-Oriented Programming using C++

5. SUMMARY
Let us recapitulate the important points discussed in this unit:

• In this unit, learners have studied the operators in C++, including arithmetic, logical, and relational
operators, which are essential for performing different operations within expressions.
• Learners have studied the new operators unique to C++, such as the scope resolution operator,
which allows access to global variables and specific class members, and member dereferencing
operators that facilitate the manipulation of pointers to class members.
• Memory management operators like new and delete are explored, providing learners with the
tools to dynamically allocate and deallocate memory, a crucial aspect of efficient programming.
• Manipulators, such as endl and setw, are also covered, demonstrating how to format output in a
controlled and readable manner.
• The structure of a C++ program is then examined, highlighting the importance of preprocessor
directives, the main() function, and other components that contribute to a well-organized and
maintainable codebase. Learners will also be guided through the process of compiling and
executing C++ programs, learning to identify and resolve errors during the compilation process to
ensure their programs run as intended.
• conditional control statements, such as if, else, and switch, which are fundamental for
implementing decision-making logic within programs. These control structures enable the
creation of dynamic and responsive software that can adapt to different inputs and conditions.

Unit: 3 - Operators and Program Structure in C++ 34


DCA1210: Object-Oriented Programming using C++

6. SELF-ASSESSMENT QUESTIONS
Multiple choice Questions
1 Which operator is used to access a global variable when a local variable has the same name?
a) ::
b) *
c) ->
d) .
2 Which of the following is a memory management operator in C++?
a) new
b) delete
c) malloc
d) Both a and b
3 The setw manipulator is used to:
a) Set the precision of floating-point numbers
b) Set the width of the output field
c) Insert a newline in the output
d) Align text to the left
4 Which conditional control statement is used to choose between multiple cases based on the
value of an expression?
a) if
b) else
c) switch
d) for
True or False:

5 The delete operator is used to allocate memory in C++.

6 Conditional control statements like if and switch allow a program to make decisions based on
conditions.
Fill in the Blanks:

7 The ____ statement is used to exit from a loop or switch statement.

8 In C++, the ____ manipulator is used to insert a line break in the output.

Unit: 3 - Operators and Program Structure in C++ 35


DCA1210: Object-Oriented Programming using C++

9 What is the default return type of the main() function in C++?

10 Which operator is used to access a class member using a pointer to an object?

Unit: 3 - Operators and Program Structure in C++ 36


DCA1210: Object-Oriented Programming using C++

7. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective

Symbols used in C++ to perform operations on variables and values, such


Operators -
as +, -, *, /, and %.

A combination of operators and operands that evaluates to a single value,


Expressions -
such as a + b or x * y - z.

Operators used to perform basic mathematical operations, including


Arithmetic
- addition (+), subtraction (-), multiplication (*), division (/), and modulus
Operators
(%).

Relational Operators that compare two values and return a boolean result, such as
-
Operators greater than (>), less than (<), equal to (==), and not equal to (!=).

Operators used to perform logical operations, often in control statements,


Logical Operators -
such as AND (&&), OR (||), and NOT (!).

Scope Resolution An operator used to access global variables or class members when there
-
Operator (::) is a conflict with local variables.

Member
Operators used to access members of a class or structure through
Dereferencing -
pointers, such as -> and .*.
Operators

Pointer-to-Member An operator used to access a class member through a pointer to the


-
Operator (->*) member.

Memory
Operators in C++ used to dynamically allocate and deallocate memory,
Management -
specifically new and delete.
Operators

An operator used to allocate memory dynamically for a variable or object


new Operator -
at runtime.

delete Operator - An operator used to free the memory allocated by new.

Functions or operators that modify the formatting of input and output


Manipulators -
streams, such as endl, setw, and setprecision.

Unit: 3 - Operators and Program Structure in C++ 37


DCA1210: Object-Oriented Programming using C++

A manipulator that inserts a newline character in the output and flushes


endl Manipulator
the output buffer.

A manipulator that sets the width of the next output field, useful for
setw Manipulator
formatting text in columns.

A declarative region that provides scope to identifiers, preventing naming


Namespace
conflicts, commonly used as std in C++.

The process of converting C++ source code into machine code (object
Compiling
code) by the compiler.

The process of combining object files and libraries into a single executable
Linking
program.

Conditional Control Statements that execute different blocks of code based on the evaluation
Statements of conditions, such as if, else, and switch.

A control statement that allows a variable to be tested for equality against


Switch Statement -
a list of values, executing different blocks of code based on the match.

Unit: 3 - Operators and Program Structure in C++ 38


DCA1210: Object-Oriented Programming using C++

8. TERMINAL QUESTIONS
1. Explain the use of the scope resolution operator in C++ with an example.
2. What are manipulators in C++? Discuss the endl and setw manipulators with examples.
3. Describe the structure of a C++ program, highlighting the role of each component.
4. Explain the role of memory management operators (new and delete) in C++.
5. Write a short C++ program that demonstrates the use of conditional control statements (if-else).
6. Explain how the switch statement works in C++ and provide a brief example.
7. Describe the importance of compiling and linking in the C++ programming process.
8. Discuss the concept of expressions in C++ and how operators are used to form them.
9. Write a detailed explanation on the role of manipulators in C++. Provide examples to show how
manipulators like setw, and endl are used in formatting output.
10. Develop a C++ program that reads a number from the user and determines if it is even or odd
using conditional statements.

Unit: 3 - Operators and Program Structure in C++ 39


DCA1210: Object-Oriented Programming using C++

9. ANSWERS
Self-Assessment Questions
1. ::
2. Both a and b
3. Set the width of the output field
4. Switch
5. Break
6. Endl
7. Int
8. ->
9. False
10. True

Terminal Questions Answers


1. Refer to Section 3.2.2
2. Refer to Section 3.2.2
3. Refer to Section 3.3
4. Refer to Section 3.2.2
5. Refer to Section 3.4.1
6. Refer to Section 3.4.1
7. Refer to Section 3.4
8. Refer to Section 3.2.1
9. Refer to Section 3.2.2
10. Refer to Section 3.4.1

Unit: 3 - Operators and Program Structure in C++ 40


DCA1210: Object-Oriented Programming using C++

10. REFERENCES
1. E Balagurusamy, “Object-Oriented Programming with C++”, 8th edition, 2020, Tata McGraw Hill
Publications.
2. Object-Oriented Programming Using C++, By B. Chandra, CRC Press.
3. Starting Out with C++: From Control Structures Through Objects, Global Edition, by Tony Gaddis,
Pearson Education.

Unit: 3 - Operators and Program Structure in C++ 41


DCA1210: Object-Oriented Programming using C++

BACHELOR OF COMPUTER APPLICATIONS


SEMESTER 2

DCA1210
OBJECT - ORIENTED PROGRAMMING
Unit: 4 - Type Casting and Pointers inUSING
C++ C++ 1
DCA1210: Object-Oriented Programming using C++

Unit – 4
Type Casting and Pointers in C++

Unit: 4 - Type Casting and Pointers in C++ 2


DCA1210: Object-Oriented Programming using C++

TABLE OF CONTENTS

Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4-5
1.1 Objectives - -
2 Type Conversion - -

2.1 Implicit Conversion - -


6 - 12
2.2 Explicit Conversion (Type Casting) - -

2.3 Conversion using Cast Operator - -


3 Pointers - -
13 - 16
3.1 Declaration and initialisation of pointers - -
4 Memory Allocation - -

4.1 Dynamic Memory Allocation - - 17 - 20

4.2 Memory Deallocation - -


5 Summary - - 21
6 Self-Assessment Questions - 1 22 - 24
7 Glossary - - 25 - 26
8 Sample Programs - - 27 - 31
9 Terminal Questions - - 32
10 Answers - - 33
11 References - - 34

Unit: 4 - Type Casting and Pointers in C++ 3


DCA1210: Object-Oriented Programming using C++

1. INTRODUCTION
In the previous unit 3, learners have studied various operators in C++, including expressions and new
operators like the scope resolution operator, member dereferencing operators, and memory
management operators. They also explored the structure of a C++ program, how to compile and
execute it, and the use of manipulators for formatting output and also they gained an understanding
of conditional control statements such as if, else, and switch, which are essential for decision-making
in programs.

In this unit, learners will explore the fundamental concepts of Type Casting and Pointers in C++, which
are essential for effective memory management and type manipulation in programming. The unit
begins with an exploration of Type Casting, where learners will understand how to convert data types
explicitly and implicitly, enabling more flexible and precise control over variables in their programs.

They also learn about Pointers, a powerful feature in C++ that allows direct access and manipulation
of memory addresses. Learners will understand how to declare and initialise pointers, which are
crucial for working with dynamic data structures and functions. The unit will then advance to
Dynamic Memory Allocation, where learners will discover how to allocate memory dynamically at
runtime using pointers, allowing them to manage memory more efficiently in complex applications.
Finally, the unit will cover Memory Deallocation, teaching learners the importance of freeing up
dynamically allocated memory to prevent memory leaks and ensure optimal program performance.

To study this unit, learners must understand the differences between implicit and explicit type casting
through hands-on practice. When studying pointers, consider how they are declared, initialised, and
used in memory management. Practice dynamic memory allocation and deallocation using new and
delete to prevent memory leaks. Regular coding exercises and testing with real examples will
reinforce these concepts and ensure a solid understanding of type casting and pointers in C++.

Unit: 4 - Type Casting and Pointers in C++ 4


DCA1210: Object-Oriented Programming using C++

1.1. Objectives
After studying this unit, you should be able to:
• list the different types of type casting available
in C++
• Explain how pointers are used to reference and
manipulate memory locations in C++.
• Explain how dynamic memory allocation works
in C++.
• Analyze programs to identify potential memory
leaks and improper memory deallocation
practices.

Unit: 4 - Type Casting and Pointers in C++ 5


DCA1210: Object-Oriented Programming using C++

2. TYPE CONVERSION
Type conversion refers to converting a value from one data type to another. This conversion can be
implicit (automatically handled by the compiler) or explicit (managed by the programmer through
type casting).

There are two types of type conversion:


i. Implicit Type Conversion
ii. Explicit Type Conversion

2.1. Implicit Type Conversion


Implicit type conversion is automatically performed by the compiler when it encounters an
expression involving different data types i.e., the programmer doesn't need to manually cast the types;
the compiler handles it.

In expressions where different data types are present, the compiler promotes smaller data types to
larger ones to prevent data loss. This process is also called type promotion. The data types of all
variables are promoted to the data type of the variable with the highest data type.

Example:
bool -> char -> short int -> int -> unsigned int -> long -> unsigned ->
long long -> float -> double -> long double

The above example shows a hierarchy of types, indicating the order in which types are promoted
during implicit conversion. For example, bool can be promoted to char, which can then be promoted
to short int, and so on up to long double.

Implicit conversions can sometimes result in loss of information. For example, converting from a
signed to an unsigned type can lose the sign, and converting from a larger type to a smaller type can
result in overflow.

// An example of implicit conversion


#include <iostream>
using namespace std;

int main()
{

Unit: 4 - Type Casting and Pointers in C++ 6


DCA1210: Object-Oriented Programming using C++

int x = 10; // integer x


char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
cout << "x = " << x << endl
<< "y = " << y << endl
<< "z = " << z << endl;
return 0;
}

In the code, we start with two variables: x, an integer initialized to 10, and y, a character holding the
letter 'a'. When we add x and y together, the character 'a' is automatically converted to its ASCII value,
which is 97. So, x becomes 107 after the addition.

Next, we add x to 1.0, a floating-point number. Here, the integer x is converted to a float before the
addition, resulting in a floating-point value 108.0, which is stored in z.

Finally, the program prints the values of x, y, and z. The output shows x as 107, y as 'a', and z as 108.0.
This example illustrates how C++ automatically handles different data types during calculations to
ensure the operations are performed correctly, without requiring explicit type conversion by the
programmer.

Output:
x = 107
y=a
z = 108

2.2. Explicit Type Conversion


They are referred to as type casting, which is a process in C++ where the programmer explicitly
converts a value from one data type to another. Unlike implicit conversion, where the compiler
automatically converts types, explicit conversion is controlled by the user and can be applied where
needed.

Unit: 4 - Type Casting and Pointers in C++ 7


DCA1210: Object-Oriented Programming using C++

In explicit type conversion, the user specifies the desired data type directly in the code, ensuring that
the result of an expression is of a particular type. This is especially useful when the automatic type
conversion provided by the compiler is not sufficient or when precise control over the type
conversion is required.

One common method of explicit conversion in C++ is by using the cast operator, which involves
placing the desired type in parentheses before the expression. This is known as "forceful casting"
because it overrides the default type conversion that the compiler would normally perform.

Syntax:
(type) expression

Where, ‘type’ is the data type you want the expression to be converted to, and expression is the value
or operation being cast.

Example:
int a = 10;
double b = 3.14;
int c = (int) b; // Explicitly casting the double b to an int

In the above example, b, which is a double, is explicitly converted to an integer type before it is
assigned to c. The fractional part of b (which is .14) is discarded during this conversion, resulting in c
being equal to 3.

Explicit type conversion is powerful, but it must be used carefully. Improper use can lead to data loss
or unexpected results, particularly when converting between types that have different ranges or
precision (like converting a floating-point number to an integer).

// C++ program to demonstrate


// explicit type casting
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;

Unit: 4 - Type Casting and Pointers in C++ 8


DCA1210: Object-Oriented Programming using C++

return 0;
}

This C++ program explains the concept of explicit type casting, where a value of one data type is
manually converted to another type by the programmer.

In the code, a variable x is declared and initialized with the value 1.2, which is of type double. Double
is a data type that can hold floating-point numbers, meaning numbers with decimal points.

Next, the program performs an explicit conversion, also known as type casting, where the double
value x is converted into an integer type. This is done by placing (int) before the variable x. By doing
this, the decimal part of x (which is .2) is removed, leaving just 1.

After the conversion, 1 is added to 1, resulting in the sum being 2. The program then outputs this
result with the message "Sum = 2".

2.3. Conversion using Cast operator


There are different kinds of casts in C++, such as static casts, dynamic casts, reinterpret casts, and const
casts.

i. Static Cast:
The static_cast is the simplest and most commonly used type of cast in C++. It is a compile-time cast
i.e., type conversion is checked and performed by the compiler during compilation, rather than at
runtime. This type of cast is typically used for converting between related types where the conversion
is well-defined, such as between an integer and a floating-point number (like int to float), or between
pointers to related types (such as a pointer to a derived class to a pointer to a base class).

The static_cast can also be used to call explicit conversion functions, allowing for more controlled and
intentional type conversions in your code. Unlike other types of casts, static_cast does not perform
any runtime checks, so it is important to ensure that the conversion is valid, as incorrect usage can
lead to undefined behavior.

Syntax:
static_cast <new_data_type> (expression);

Example:
aCharVar = static_cast(anIntVar);

Unit: 4 - Type Casting and Pointers in C++ 9


DCA1210: Object-Oriented Programming using C++

• The above example explains the using of static_cast to convert an integer to a character. In this case,
the integer variable anIntVar is cast to the char type, allowing it to be stored in a character variable
aCharVar.
• static_cast is easy to identify in the code, making it easier to find and understand compared to older
C++ casting methods, which often blended into the surrounding code.

Example:
// cast.cpp
// tests signed and unsigned integers
#include <iostream>
using namespace std;
int main() {
int intVar = 1500000000; // 1,500,000,000
intVar = (intVar * 10) / 10; // result too large
cout << "intVar = " << intVar << endl; // wrong answer
intVar = 1500000000; // cast to double
intVar = (static_cast<double>(intVar) * 10) / 10;
cout << "intVar = " << intVar << endl; // right answer
return 0;
}

The above code shows a scenario where multiplying a large integer by 10 exceeds the capacity of an
integer variable. To overcome that the solution is to use static_cast<double> to convert the integer to
a double before performing the multiplication. This ensures that the result fits within the variable's
capacity, avoiding potential overflow errors i.e., it handle large calculations by converting the integer
variable to a double before performing the multiplication. This prevents overflow and ensures that
the result is accurate.

ii. Dynamic Cast


The dynamic_cast operator in C++ is a runtime cast specifically used for converting pointers or
references to classes. Unlike other types of casting, such as static_cast, which is checked at compile
time, dynamic_cast performs its checks at runtime i.e., it verifies whether the casting is valid when the
program is running.

Unit: 4 - Type Casting and Pointers in C++ 10


DCA1210: Object-Oriented Programming using C++

dynamic_cast is particularly useful when working with inheritance hierarchies in object-oriented


programming.

For example, if you have a base class pointer that might actually point to an object of a derived class,
dynamic_cast allows you to safely convert that base class pointer to a derived class pointer.

A key aspect of dynamic_cast is that it relies on RTTI (Runtime Type Identification), a mechanism in
C++ that keeps track of the actual types of objects during execution. If the cast is successful,
dynamic_cast returns a pointer or reference to the requested derived type.

If the cast fails—meaning the object isn't of the type you're trying to cast to—dynamic_cast returns
nullptr for pointers or throws a std::bad_cast exception for references.

iii. Const Cast


const_cast is a type of casting operator in C++ that allows you to modify the const qualifier of a variable.
It enables user to override the const behavior, either by adding or removing the const attribute of a
pointer or reference. This is particularly useful in scenarios where you need to modify an object that
was initially declared as const, or where you want to pass a const object to a function that does not
accept const parameters.

const_cast Works by:

• Adding const to a Non-const Pointer: You can use const_cast to convert a non-const pointer into
a const pointer. This might be useful when you want to ensure that certain parts of your code do
not modify an object, while other parts do.

Example:
int value = 42;
int* ptr = &value; // non-const pointer
const int* constPtr = const_cast<const int*>(ptr); // add const to pointer

In this example, const_cast is used to add the const qualifier to the pointer ptr, ensuring that the object
value cannot be modified through constPtr.

• Removing const from a Const Pointer: The more common use of const_cast is to remove the
const qualifier from a pointer or reference, allowing modification of an object that was originally
declared as const.

Example:
const int value = 42;

Unit: 4 - Type Casting and Pointers in C++ 11


DCA1210: Object-Oriented Programming using C++

const int* constPtr = &value; // const pointer


int* nonConstPtr = const_cast<int*>(constPtr); // remove const from pointer
*nonConstPtr = 24; // modify the value

Here, const_cast is used to remove the const qualifier from the pointer constPtr. This allows the
program to modify the value of value through nonConstPtr. However, doing so is risky because value
was originally declared as const, and modifying it after removing const can lead to undefined behavior.

iv. Reinterpret cast:


reinterpret_cast is a special tool in C++ that lets you change a pointer of one type into a pointer of a
completely different type. This means you can make a pointer to one kind of data (like an integer)
behave like it's a pointer to another kind of data (like a character).

When you use reinterpret_cast, it doesn't check whether the original type and the new type of the
pointer make sense together. It just changes the pointer to the new type without any checks.

Syntax:
data_type *var_name = reinterpret_cast<data_type *>(pointer_variable);

Where,data_type is the type you want the pointer to change into.

pointer_variable is the original pointer that you want to change.

Unit: 4 - Type Casting and Pointers in C++ 12


DCA1210: Object-Oriented Programming using C++

3. POINTERS
Pointers are a very powerful feature of the language with many uses in programming. Pointer is a
variable that stores the address of another variable.

Some of the programing tasks are performed more easily with pointers such as dynamic memory
allocation (i.e. obtaining memory at runtime from the system).

As you know, every variable created in a program is stored in the memory.

The location of memory in a system can be accessed through the address.

The address of a variable can be accessed using ampersand (&) operator.

If there is an integer variable named P in the program, and if you have statement cout<<&P, the
program will display the address of the variable P, which will be a hexadecimal number.

3.1. Declaration and Initialization of pointers


Pointers are variables that store address values of other variables. They are defined by prefixing “*”
(asterisk) to the variable name. The data type of the pointer variable can be any of the basic or user-
defined data type, or even void. If a pointer is defined as a particular data type, then it can store
addresses of variables of that data type alone. However, if the pointer is defined as void, then it can
store addresses of variables of any data type.

The following statements create a pointer ptr and assign the address of the integer variable P. The
declaration of pointer variable is the same as any other variable, except that you add an asterisk
before the name of the pointer variable,

int *ptr;
int P=5;
ptr=&P;

The variable P can be accessed by two ways now: one, through the name P and the other, through the
pointer.

The following statement displays the contents of P through the pointer ptr. cout<<*ptr;

Here, * is known as the indirection operator or value of the variable pointed to by the pointer.

If you use cout<<ptr; statement in the program, it will simply display the address of the P or the
contents stored in the ptr variable.

Unit: 4 - Type Casting and Pointers in C++ 13


DCA1210: Object-Oriented Programming using C++

One of the important uses of pointers is getting memory during runtime. Pointer can be used with
arrays. Both are related to each other. Arrays work similar to pointer to their first element. So, an
array can always be implicitly converted to the pointer of the proper type.

Example:
Let us declare two variables one is pointer type and another one is array type.

int * A;
int B [10];

As we have already studied with regard to the array, brackets ([]) are used to specify the size of an
array. We can assign pointer variable to an array. So, the following assignment statement is valid.

A=B;

Pointers and arrays support the same set of operations, with the same meaning for both. The main
difference is that the pointers can be assigned new addresses, while the arrays cannot.

Following example illustrates the use of pointers and arrays

#include <iostream>
using namespace std;
int main()
{
int A[5]; // Array declaration
int* p; // Pointer declaration
p = A; // Point to the first element of the array
*p = 10; // A[0] = 10
p++; // Move the pointer to the next element (A[1])
*p = 20; // A[1] = 20
p = &A[1]; // Point to the second element (A[1])
p++; // Move the pointer to the third element (A[2])
*p = 30; // A[2] = 30
p = &A[2]; // Point to the third element (A[2])
// Print the first three elements of the array
for (int n = 0; n < 3; n++) {
cout << A[n] << ", ";
}

Unit: 4 - Type Casting and Pointers in C++ 14


DCA1210: Object-Oriented Programming using C++

return 0;
}

Output:
10, 20, 30,

In the program given above, the statement p=A assigns values of an array to a pointer.

When Pointer p increments, address of pointer will move to the next address location. Here value of
the array is assigned to the pointer. Using for loop, the program displays array values.

If we know the size of an array, we can easily assign values to the array using index without wastage
of memory. When there is no idea about the size of an array in advance, array can be declared using
pointer.

• The program initializes an array A of 5 integers.


• It uses a pointer p to manipulate elements of the array A.
• The pointer is first set to the beginning of the array and assigns values 10, 20, and 30 to the first
three elements of the array.
• Finally, the program prints out the first three elements of the array, separated by commas.

Pointer uses “New” operator to allocate memory to array during runtime and returns the memory
location of the first element in the array. Using new operator, we can create (allocate) and delete
(destroy) the objects dynamically.

The syntax of the new operator is:


Pointervariable = new data type [size];

where data type can be any basic or user-defined and the size is any integer value.

Delete operator is used to return the memory to the system. The syntax of delete operator is:

delete pointervariable;

where pointervariable is the pointer containing address returned by the system.

The following program creates a dynamic array, and finds the sum of array elements:

#include <iostream>
using namespace std;
int main()
{

Unit: 4 - Type Casting and Pointers in C++ 15


DCA1210: Object-Oriented Programming using C++

int n, sum = 0;
int* ptr;
cout << "Enter the size of the array: " << endl;
cin >> n;
ptr = new int[n]; // dynamically allocate memory for array
cout << "Enter " << n << " numbers: ";
for (int i = 0; i < n; i++) {
cin >> ptr[i];
sum = sum + ptr[i];
}
cout << "Sum = " << sum << endl;
delete[] ptr; // properly deallocate memory
// cin.get(); // if you want to pause the program to see the output
return 0;
}

Output:
Enter the size of the array:
5
Enter 5 numbers: 1 2 3 4 5
Sum = 15

In the program given above, the statement ptr=new int[n]; asks the system to allocate memory of size
n. It stores integer values and stores the address of the memory allotted in the pointer variable ptr.

Unit: 4 - Type Casting and Pointers in C++ 16


DCA1210: Object-Oriented Programming using C++

4. MEMORY ALLOCATION
Memory allocation refers to the process of reserving or providing space for variables in a program. It
is essential for storing data during the execution of a program.

Static Allocation (Compile-time Allocation): Static memory allocation occurs when the size and data
type of a variable are known at compile-time. This type of memory allocation is fixed and does not
change throughout the execution of the program. For example, when you declare a variable like

int x = 5;

the memory for x is allocated statically.

4.1. Dynamic Allocation (Run-time Allocation):


Dynamic memory allocation occurs during the execution of a program, allowing the program to
allocate memory as needed, even when the exact size of the variable is not known in advance. Pointers
are crucial for dynamic memory allocation, as they store the address of the dynamically allocated
memory.

Dynamic memory allocation is necessary when the size of data is not known beforehand or when
memory needs to be allocated while the program is running. This flexibility allows programs to
handle variable-sized data efficiently. The two main reasons for using dynamic memory allocation
are:

The need for a dynamic space in memory.

The requirement to store the address to access the variable in memory.

Memory De-allocation:
Just as memory can be dynamically allocated, it can also be dynamically de-allocated to free up space
when it is no longer needed. This is essential for efficient memory management and avoiding memory
leaks.

Dynamic Memory Allocation Using the new Operator:


• The new operator is used to allocate memory dynamically. When you use new, you request a
block of memory from the heap, and if successful, it returns the address of that memory block,
which can be stored in a pointer variable.

Unit: 4 - Type Casting and Pointers in C++ 17


DCA1210: Object-Oriented Programming using C++

Syntax:
Pointer_variable = new data_type;

Where, Pointer_variable is a pointer of a specific data type that stores the address of the newly
allocated memory.

Example:
int *m = NULL; // Initially, m is a NULL pointer
m = new int; // Memory is dynamically allocated for an int and the address is stored in m

Alternatively, you can declare and allocate memory in one line:

int *m = new int;

Initializing Memory with new


In C++, the new operator not only allocates memory dynamically but can also initialize it. This is
particularly useful for creating arrays or other blocks of memory at runtime when the size of the data
may not be known at compile time.

Example of Initializing Memory:


Dynamic Array Allocation: int *arr = new int[10];

In this example, memory for an array of ten integers is dynamically allocated. The new operator
returns a pointer to the first element of the array, which is stored in the pointer variable arr. Here,
arr[0] refers to the first element, arr[1] to the second, and so on.

4.2. Memory Deallocation


You must use the delete[] operator to free the memory for dynamically allocated arrays.

delete[ ] arr;

This ensures that the memory is returned to the heap and can be reused by other parts of the program
or other programs running on the system.

Handling Allocation Failures:


If there is not enough space in the heap to fulfill a new request, the allocation will fail and throw an
exception of type std::bad_alloc. This is important to handle, especially in systems where memory
resources are limited.

To handle allocation failures gracefully, you can check if the allocation was successful:

int *arr = new (std::nothrow) int[10];

Unit: 4 - Type Casting and Pointers in C++ 18


DCA1210: Object-Oriented Programming using C++

if (!arr) {
// Handle allocation failure
std::cerr << "Memory allocation failed!" << std::endl;
}

Using std::nothrow ensures that instead of throwing an exception, new returns a nullptr if the
allocation fails. This allows you to check the pointer and handle the failure appropriately.

Example:
#include <iostream>
#include <new> // Required for std::nothrow
int main() {
// Dynamically allocate memory for an array of 10 integers
int *arr = new (std::nothrow) int[10];
// Check if the allocation was successful
if (!arr) {
std::cerr << "Memory allocation failed!" << std::endl;
return 1; // Exit the program with an error code
}
// Initialize the array
for (int i = 0; i < 10; ++i) {
arr[i] = i * 10; // Assign values to each element
}
// Print the array
for (int i = 0; i < 10; ++i) {
std::cout << "arr[" << i << "] = " << arr[i] << std::endl;
}
// Deallocate the memory
delete[] arr;
return 0; // Exit the program successfully
}

Output:
arr[0] = 0
arr[1] = 10

Unit: 4 - Type Casting and Pointers in C++ 19


DCA1210: Object-Oriented Programming using C++

arr[2] = 20
arr[3] = 30
arr[4] = 40
arr[5] = 50
arr[6] = 60
arr[7] = 70
arr[8] = 80
arr[9] = 90

The above C++ program that demonstrates how to dynamically allocate memory for an array using
the new operator, how to initialize the elements of the array, and how to safely handle memory
allocation failures. The program begins by attempting to allocate memory for an array of 10 integers
using the new operator along with the std::nothrow option. This option ensures that if the allocation
fails (due to insufficient memory), the new operator will return a nullptr instead of throwing an
exception, allowing the program to handle the failure gracefully.

After the memory allocation, the program checks whether the allocation was successful by verifying
if the pointer arr is not nullptr. If the allocation fails, the program outputs an error message to the
standard error stream and exits with an error code. If the allocation is successful, the program
proceeds to initialize the array elements by assigning each element a value that is ten times its index
(e.g., arr[0] = 0, arr[1] = 10, and so on).

Once the array is initialized, the program prints the values of all 10 elements to the console. After
displaying the array contents, the program deallocates the memory that was dynamically allocated
using the delete[] operator. This is an essential step to prevent memory leaks, as it frees up the
allocated memory so that the system can reuse it.

Finally, the program exits successfully. This code illustrates good practices in dynamic memory
management, including checking for successful memory allocation, properly initializing allocated
memory, and ensuring that dynamically allocated memory is freed when it is no longer needed.

Unit: 4 - Type Casting and Pointers in C++ 20


DCA1210: Object-Oriented Programming using C++

5. SUMMARY
Let us recapitulate the important points discussed in this unit:

• In this unit learners have studied the critical concepts in C++ programming like Type Casting and
Pointers, which are essential for advanced memory management and data manipulation.
• Type Casting, where learners will studied the differences between implicit and explicit casting.
The compiler automatically handles implicit casting, while explicit casting, using operators like
static_cast, dynamic_cast, const_cast, and reinterpret_cast, allows the programmer to convert data
types deliberately, ensuring the correct handling of data in various contexts.
• Pointers, that allows direct access to memory locations. Learners will gain a solid understanding
of how to declare and initialize pointers, which are crucial for managing dynamic data structures
and functions efficiently. Pointers enable advanced operations such as pointer arithmetic,
referencing, and dereferencing, which are fundamental in C++ for working with arrays, dynamic
memory, and complex data structures like linked lists.
• Dynamic Memory Allocation, a technique that allows memory to be allocated during runtime using
pointers. This is particularly useful when the exact amount of memory required is not known at
compile time. Learners have studied how to use the new operator to allocate memory dynamically
and the importance of managing this memory correctly.
• Memory Deallocation emphasises the importance of freeing up dynamically allocated memory
using the delete and delete[] operators to prevent memory leaks, which can lead to inefficient
memory usage and program instability. Learners have understood, how to effectively manage and
deallocate memory, ensuring their programs run efficiently and reliably.

Unit: 4 - Type Casting and Pointers in C++ 21


DCA1210: Object-Oriented Programming using C++

6. SELF-ASSESSMENT QUESTIONS
Multiple choice Questions
1 Which operator is used for explicit type casting in C++?
a) ->
b) static_cast
c) sizeof
d) &
2 What does reinterpret_cast do in C++?
a) It converts data types with no runtime checks.
b) It checks at runtime before converting.
c) It converts integer to floating-point types only.
d) It cannot cast pointers.
3 Which cast would you use to remove the const qualifier from a variable?
a) static_cast
b) dynamic_cast
c) const_cast
d) reinterpret_cast
4 When should dynamic_cast be used?
a) When casting between primitive data types.
b) When casting between unrelated types.
c) When casting within an inheritance hierarchy.
d) When removing const from a pointer.
5 What type of memory is allocated using the new operator?
a) Stack
b) Heap
c) Register
d) Static
6 What happens if new fails to allocate memory?
a) Returns 0
b) Throws an exception
c) Halts the program

Unit: 4 - Type Casting and Pointers in C++ 22


DCA1210: Object-Oriented Programming using C++

d) Returns NULL

7 Which keyword is used to deallocate memory allocated with new?


a) free
b) delete
c) release
d) clear
8 What is the default value of a pointer when it is declared but not initialized?
a) 0
b) null
c) nullptr
d) Undefined
9 What is the correct syntax to dynamically allocate an array of 10 integers?
a) int arr[10] = new int[];
b) int* arr = new int[10];
c) int arr = new int(10);
d) int* arr = new int* [10];
10 How do you release memory allocated for an array in C++?
a) free(arr);
b) delete arr;
c) delete[] arr;
d) release(arr);
11 Which operator is used to obtain the address of a variable?
a) *
b) &
c) @
d) #
12 Which operator is used to dereference a pointer in C++?
a) *
b) &
c) ->
d) .
13 What will be the output of int x = 10; float y = static_cast<float>(x); cout << y;?

Unit: 4 - Type Casting and Pointers in C++ 23


DCA1210: Object-Oriented Programming using C++

a) 10
b) 10.0
c) 0
d) undefined
Fill in the Blanks:

14 What exception is thrown when new fails to allocate memory?

15 What is the keyword used to prevent exceptions on failure during memory allocation?

Unit: 4 - Type Casting and Pointers in C++ 24


DCA1210: Object-Oriented Programming using C++

7. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective

Type Casting - The process of converting a variable from one data type to another.

Implicit Type Automatic conversion of one data type to another by the compiler without
-
Casting explicit instructions from the programmer.

Explicit Type Manual conversion of one data type to another using casting operators
-
Casting like static_cast, dynamic_cast, const_cast, and reinterpret_cast.

A type casting operator used for converting between related types at


static_cast -
compile time.

A type casting operator used to safely convert pointers and references


dynamic_cast -
within an inheritance hierarchy at runtime.

A type casting operator used to add or remove the const qualifier from a
const_cast -
variable.

A type casting operator that converts any pointer type to any other
reinterpret_cast -
pointer type, even if the types are unrelated.

RTTI (Runtime A mechanism in C++ that provides information about the dynamic type of
-
Type Identification) an object at runtime, often used with dynamic_cast.

The operator used to explicitly convert a data type to another, such as


Cast Operator -
static_cast, dynamic_cast, const_cast, and reinterpret_cast.

Pointer - A variable that stores the memory address of another variable.

The process of accessing the value stored at the memory address held by
Dereferencing -
a pointer using the * operator.

A pointer that points to no valid memory location, often represented by


Null Pointer -
nullptr in C++.

Dynamic Memory The process of allocating memory during runtime using operators like
-
Allocation new and delete.

Unit: 4 - Type Casting and Pointers in C++ 25


DCA1210: Object-Oriented Programming using C++

The region of memory used for dynamic memory allocation, where blocks
Heap Memory -
of memory are allocated and deallocated as needed.

new Operator - An operator in C++ used to allocate memory dynamically on the heap.

A keyword used with the new operator to return a nullptr instead of


nothrow -
throwing an exception if memory allocation fails.

An array whose size is determined at runtime and allocated on the heap


Dynamic Array -
using the new operator.

A situation where dynamically allocated memory is not properly


Memory Leak -
deallocated, leading to wasted memory that the program cannot reuse.

std::bad_alloc - An exception thrown when the new operator fails to allocate memory.

Memory The process of releasing memory that was previously allocated


-
Deallocation dynamically, returning it to the system for future use.

An operator used to free memory that was allocated dynamically using


delete Operator -
the new operator.

An operator used to free memory allocated for arrays using the new[]
delete[] Operator -
operator.

Unit: 4 - Type Casting and Pointers in C++ 26


DCA1210: Object-Oriented Programming using C++

8. SAMPLE PROGRAMS
1. Write a C++ program to demonstrate the use of static_cast.
#include <iostream>
using namespace std;
int main() {
int intValue = 10;
double doubleValue;
// Convert int to double using static_cast
doubleValue = static_cast<double>(intValue);
cout << "Integer value: " << intValue << endl;
cout << "Converted double value: " << doubleValue << endl;
// Example of static_cast with pointers
void* ptr = &intValue; // void pointer pointing to an int
int* intPtr = static_cast<int*>(ptr); // static_cast to int pointer
cout << "Pointer value (as void*): " << ptr << endl;
cout << "Pointer value (as int*): " << intPtr << endl;
cout << "Value pointed by intPtr: " << *intPtr << endl;
return 0;
}

Output:
Integer value: 10
Converted double value: 10
Pointer value (as void*): 0x7ffd82628d14
Pointer value (as int*): 0x7ffd82628d14
Value pointed by intPtr: 10

2. Write a C++ program to declare and initialize a pointer.


#include <iostream>
using namespace std;
int main() {
// Declare an integer variable
int num = 10;

Unit: 4 - Type Casting and Pointers in C++ 27


DCA1210: Object-Oriented Programming using C++

// Declare a pointer variable and initialize it to point to num


int* ptr = &num;
// Output the value of num using the pointer
cout << "Value of num: " << num << endl;
cout << "Value pointed to by ptr: " << *ptr << endl;
// Output the address of num
cout << "Address of num: " << &num << endl;
// Output the value stored in ptr (which is the address of num)
cout << "Value of ptr (address of num): " << ptr << endl;
return 0;
}

Output:
Value of num: 10
Value pointed to by ptr: 10
Address of num: 0x7ffc60849e54
Value of ptr (address of num): 0x7ffc60849e54

3. C++ Program to Dynamically Allocate Memory for an Array of Integers Using the new
Operator
#include <iostream>
using namespace std;
int main() {
int n;
// Ask the user for the size of the array
cout << "Enter the number of elements in the array: ";
cin >> n;
// Dynamically allocate memory for the array
int* arr = new int[n];
// Input elements into the array
cout << "Enter " << n << " integers:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

Unit: 4 - Type Casting and Pointers in C++ 28


DCA1210: Object-Oriented Programming using C++

// Output the elements of the array


cout << "The elements in the array are: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Deallocate memory
delete[] arr;
return 0;
}

Output:
Enter the number of elements in the array: 5
Enter 5 integers:
16245
The elements in the array are: 1 6 2 4 5

4. C++ Program to Deallocate Memory Using the delete[ ]


#include <iostream>
using namespace std;
int main() {
int n;
// Ask the user for the size of the array
cout << "Enter the number of elements in the array: ";
cin >> n;
// Dynamically allocate memory for the array
int* arr = new int[n];
// Input elements into the array
cout << "Enter " << n << " integers:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// Output the elements of the array
cout << "The elements in the array are: ";

Unit: 4 - Type Casting and Pointers in C++ 29


DCA1210: Object-Oriented Programming using C++

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


cout << arr[i] << " ";
}
cout << endl;
// Deallocate memory
delete[] arr;
cout << "Memory deallocated successfully." << endl;
return 0;
}

Output:
Enter the number of elements in the array: 5
Enter 5 integers:
1
2
3
4
5
The elements in the array are: 1 2 3 4 5
Memory deallocated successfully.

5. C++ Program to Demonstrate nothrow Keyword with the new Operator


#include <iostream>
#include <new> // Required for std::nothrow
using namespace std;
int main() {
int n = 1000000000; // Large size to simulate possible memory allocation failure
// Attempt to allocate memory with nothrow
int* arr = new(nothrow) int[n];
if (!arr) {
cout << "Memory allocation failed!" << endl;
} else {
cout << "Memory allocation succeeded." << endl;
// Normally you'd use the array here

Unit: 4 - Type Casting and Pointers in C++ 30


DCA1210: Object-Oriented Programming using C++

// Deallocate memory if allocation succeeded


delete[ ] arr;
}
return 0;
}

Output:
Memory allocation succeeded.

Unit: 4 - Type Casting and Pointers in C++ 31


DCA1210: Object-Oriented Programming using C++

9. TERMINAL QUESTIONS
1. Explain the difference between implicit and explicit type casting in C++ with examples.
2. Write a C++ program to demonstrate the use of static_cast. Explain how the cast works.
3. Discuss the purpose and usage of const_cast in C++.
4. What is reinterpret_cast in C++? Explain its purpose and when it should be used.
5. Explain the concept of a pointer in C++. Write a C++ program to declare and initialize a pointer.
6. Write a C++ program to dynamically allocate memory for an array of integers using the new
operator.
7. Describe the process of memory deallocation in C++. Write a program to deallocate memory using
the delete[] operator.
8. Describe how to use the nothrow keyword with the new operator. Write a program to
demonstrate it.
9. What is the significance of runtime type identification (RTTI) in C++? How does dynamic_cast
utilize RTTI?
10. Discuss the best practices for managing dynamic memory in C++ to prevent memory leaks and
undefined behavior.

Unit: 4 - Type Casting and Pointers in C++ 32


DCA1210: Object-Oriented Programming using C++

10. ANSWERS
Self-Assessment Questions
1. static_cast
2. It converts data types with no runtime checks.
3. const_cast
4. When casting within an inheritance hierarchy.
5. Heap
6. Throws an exception
7. Delete
8. Undefined
9. int* arr = new int[10];
10. delete[] arr;
11. &
12. *
13. 10.0
14. std::bad_alloc
15. nothrow

Terminal Questions Answers


1. Refer to section 4.2.1 and 4.2.2
2. Refer to section 4.2.3
3. Refer to section 4.2.3
4. Refer to section 4.2.3
5. Refer to section 4.3
6. Refer to section 4.4.1
7. Refer to section 4.4.2
8. Refer to section 4.4.2
9. Refer to section 4.2.3
10. Refer to section 4.4.1

Unit: 4 - Type Casting and Pointers in C++ 33


DCA1210: Object-Oriented Programming using C++

11. REFERENCES
1. Robert Lafore, "Object-Oriented Programming in C++", Fourth Edition,Sams Publications.
2. Learning C++ Programming Concepts by Tickoo Sham, Pearson Education India.
3. C++ for Programmers by Paul Deitel, Harvey M. Deitel, Pearson Education.
4. C++ Primer Plus by Stephen Prata, Addison-Wesley Professional.
5. Object-oriented Programming with C++ - Sixth Edition by E. Balagurusamy. Tata McGraw-Hill
Education.

Unit: 4 - Type Casting and Pointers in C++ 34


DCA1210 : Object-Oriented Programming using C++
BACHELOR OF COMPUTER APPLICATION
SEMESTER 2

DCA1210
OBJECT-ORIENTED PROGRAMMING
Unit: 5 - Arrays in C++
USING C++ 1
DCA1210 : Object-Oriented Programming using C++

Unit - 5
Arrays in C++

DCA324
KNOWLEDGE MANAGEMENT
Unit: 5 - Arrays in C++ 2
DCA1210 : Object-Oriented Programming using C++

TABLE OF CONTENTS

SL Fig No / Table SAQ /


Topic Page No
No / Graph Activity

1 Introduction - -
5
1.1 Objectives - -

2 Introduction to arrays - - 6

3 Types of Arrays - -

3.1 One Dimensional Array - -

3.1.1 Input Elements in a 1D Array - -

3.1.2 Accessing 1D Array Elements - -

3.1.3 Manipulation of 1D Array - - 7-18


Elements

3.2 Multidimensional Arrays - -

3.2.1 Two- Dimensional arrays - -

3.2.2 N- Dimensional arrays - -

4 Array Operations - -

4.1 Declaration and definition of arrays - -

4.2 Initialization of an array - -

4.3 Modifying Array Elements in C++ - -


19-30
4.4 To find the maximum element - -

4.5 Reversing an Array - -

4.6 Searching for an element - -

4.7 Sorting an Array - -

5 Summary - - 31

6 Glossary - - 32

7 Self-Assessment Questions - - 33-34

Unit: 5 - Arrays in C++ 3


DCA1210 : Object-Oriented Programming using C++

8 Terminal Questions - - 35

9 Answers - - 36-39

10 References - - 40

Unit: 5 - Arrays in C++ 4


DCA1210 : Object-Oriented Programming using C++

1. INTRODUCTION
In this unit, learners will study the foundational concepts of arrays in C++, which are crucial for
organizing and managing collections of data. Arrays, as a basic data structure, allow programmers to
store multiple values of the same data type under a single name.

This unit begins by introducing the declaration and definition of arrays, explaining how they are
initialized and how their elements can be accessed. Learners will explore different ways to define
arrays and understand how arrays are utilized to efficiently handle groups of related data. This initial
section lays the groundwork for understanding the more advanced array operations covered later in
the unit.

The unit then moves into an exploration of the types of arrays, beginning with the most basic form:
the one-dimensional array. Learners will learn how to input elements into a one-dimensional array,
access individual elements, and manipulate those elements based on specific requirements. This part
of the unit focuses on practical techniques for working with one-dimensional arrays, providing
examples and exercises to ensure learners understand how to apply these concepts in programming
tasks. Following this, learners will be introduced to multidimensional arrays, which allow for more
complex data structures. Two-dimensional arrays, often used to represent tables or matrices, and N-
dimensional arrays, which extend beyond two dimensions, will be covered in detail. These arrays are
useful for handling data that is organized across multiple dimensions, and learners will gain insight
into how to manage and operate on such arrays.

As learners progress, the focus will shift to array operations, which are essential for working
effectively with arrays in C++. This section begins with the declaration and definition of arrays,
reinforcing the initial concepts while adding more depth to their application in real-world
programming. Learners will study how arrays can be initialized with specific values and how these
values can be modified after the array is created. One of the key operations learners will master is the
modification of array elements, allowing them to manipulate stored data as needed. This section
emphasizes the flexibility of arrays and how changes can be made dynamically within a program.

Further, learners will focus on more advanced operations, such as finding the maximum element
within an array. This operation involves scanning through the array to identify the largest value, a
common requirement in many programming scenarios. Reversing an array, another important
operation, will also be discussed, showing learners how to manipulate arrays in such a way that the

Unit: 5 - Arrays in C++ 5


DCA1210 : Object-Oriented Programming using C++

order of the elements is flipped. Searching for specific elements within an array will also be
introduced, providing learners with the tools to find particular values efficiently. This operation is
essential when working with large datasets where direct access to specific information is needed.

Finally, the unit will cover sorting arrays, a critical skill in programming. Learners will study simple
sorting algorithms that arrange array elements in either ascending or descending order. Sorting is a
key part of many programming tasks, as it allows for organized data handling and faster access to
desired elements.

To study this topic, learners have to focus on understanding the fundamentals of array structure,
practice array manipulation operations, and apply different types of arrays to various data problems.
It's important to write and test code to reinforce concepts like searching, sorting, and array
initialization. Regular hands-on practice with array operations will help solidify the knowledge
needed for efficient data management.

1.1 Objectives
After studying this unit, you should be able to:

• Define arrays and describe the syntax for array


declaration and initialization in C++.
• List the types of arrays (one-dimensional, two-
dimensional, and N-dimensional arrays).
• Recall the basic array operations like searching,
sorting, and finding the maximum element.
• Apply array operations like initialization, modification, and traversal in solving real-world
problems.
• Implement searching and sorting algorithms in real-world scenarios.

Unit: 5 - Arrays in C++ 6


DCA1210 : Object-Oriented Programming using C++

2. INTRODUCTION TO ARRAYS
Arrays are a fundamental data structure in programming, widely used for storing and managing
collections of elements that share the same data type. In C++, an array is a container that holds a fixed
number of values, all of which must be of the same type, such as integers, characters, or floating-point
numbers. Arrays allow for efficient data storage and easy access to individual elements through
indexing, making them a powerful tool for handling data sets in an organized manner.

The primary advantage of using arrays is their ability to store multiple values under a single variable
name. Instead of declaring multiple variables to store similar data, an array groups these values
together, making the code more compact and easier to manage. Arrays can be thought of as a
collection of contiguous memory locations where each element is stored sequentially. Each element
in the array is assigned an index, starting from 0, which allows for direct access to any value in the
array by referring to its index.

Arrays are used in a wide range of applications. For instance, they can store lists of numbers, such as
scores, temperature readings, or inventory counts. They are also ideal for working with tables, where
data is arranged in rows and columns, or for implementing matrices in mathematical computations.
The ability to access and manipulate elements in constant time, using their index, makes arrays a
preferred choice for scenarios where quick retrieval and updates are needed.

Unit: 5 - Arrays in C++ 7


DCA1210 : Object-Oriented Programming using C++

3. TYPES OF ARRAYS

Arrays can be classified based on their dimensions, which include:

3.1 One Dimensional Array


A One-Dimensional Array is a basic and straightforward type of array where data elements are stored
in a sequential, linear fashion. Each element in the array is of the same data type and is organized
under a single variable name. You can access each element individually by referencing its specific
index, which denotes its position within the array.

A one-dimensional array is like a list of items, all stored together in a single row, and you can easily
retrieve or modify any item by specifying its position in that list. This structure is particularly useful
for organizing and managing collections of related data, such as a list of numbers or a series of
characters, in a way that allows for efficient access and manipulation.

Declaration Syntax:

data_type array_name [array_size] ;

where,

o data_type specifies the type of elements that the array will hold, such as int, float, char, etc. All
elements in the array must be of this specified data type.

o array_name is the identifier or name given to the array (You will use this name to reference
the array when accessing or modifying its elements.)

o array_size defines the number of elements the array can hold. It must be an integer value and
it determines the fixed size of the array.

Example:

Int numbers[10];

Where,

o ‘int’ is the data type

o ‘Numbers’ is the name of the array

o ‘10’ is the size of the array.

Unit: 5 - Arrays in C++ 8


DCA1210 : Object-Oriented Programming using C++

Initialization Syntax

Initialization Syntax is used to assign values to a one-dimensional array at the time of its declaration.
This is a convenient way to set up an array with known values, rather than assigning values to each
element individually later in the code.

Syntax:

data_type array_name [array_size] = {comma_separated_element_list};

where,

o data_type: Specifies the type of data the array will hold, such as int, float, char, etc.

o array_name: The identifier or name you give to the array.

o array_size: The number of elements the array can hold. This value must match the number of
elements in the comma_separated_element_list.

o {comma_separated_element_list}: A list of values enclosed in curly braces {}, separated by


commas, which are assigned to the elements of the array in order.

Example:

int numbers[5] = {10, 20, 30, 40, 50};

where,

o int is the data type, meaning the array will store integers.

o numbers is the name of the array.

o 5 is the size of the array, indicating it can hold 5 integer values.

o {10, 20, 30, 40, 50} is the list of values assigned to the array elements.

Here,

• numbers[0] is assigned the value 10.

• numbers[1] is assigned the value 20.

• numbers[2] is assigned the value 30.

• numbers[3] is assigned the value 40.

• numbers[4] is assigned the value 50.

Unit: 5 - Arrays in C++ 9


DCA1210 : Object-Oriented Programming using C++

This initialization sets up the array with the specified values right at the point of declaration.
If the array size is omitted, the compiler automatically determines the size based on the
number of elements provided in the initializer list:

Example : int arr [10] ; // Declaring a 1D array of size 10

int roll_no [5] = {1, 2, 3, 4, 5} ; // Initializing a 1D array of size 5

char names[30] = {"Raj, John, Krish"} ; // Initializing a 1D array of type char

3.1.1 Input Elements in a 1D Array:


The common methods to assign and store values in a one-dimensional array. These methods include
direct initialization and user input during the program's run-time.

• Direct Initialization

• User Input Method

i. Direct Initialization

In direct initialization, the array elements are assigned values at the time of declaration. This
is a straightforward way to set up the array with known values immediately.

Example:

int num[10] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10};

Here, the array num is declared with 10 elements, and each element is assigned a specific value
directly in the code. The values {1, 3, 5, 7, 9, 2, 4, 6, 8, 10} are stored in the array in the order they are
listed. This method is useful when you know the values that need to be stored in the array beforehand.

ii. User Input Method

In this method, the program prompts the user to input the values of the array during run-time.
The user enters the values, and the program stores them in the array.

Unit: 5 - Arrays in C++ 10


DCA1210 : Object-Oriented Programming using C++

Example:

#include <iostream>

using namespace std;

int main() {

int num[5];

cout << "Enter array elements: \n";

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

cin >> num[i];

return 0;

The program first declares an array num with 5 elements. It then prompts the user to enter values for
these elements one by one. The for loop iterates 5 times (since the array has 5 elements), and during
each iteration, the user inputs a value that is stored in the respective index of the array.

This method is particularly useful when the values of the array elements are not known at compile
time and need to be provided by the user during execution.

3.1.2 Accessing 1D Array Elements


When working with a one-dimensional (1D) array in C++, we have the flexibility to access/display
either the entire array or specific elements based on your needs.

Displaying a Single Element of an Array

To display a specific element from a 1D array, you can use array indexing. Array indexing allows you
to access and print the value at a specific position in the array. It's important to remember that array
indexing in C++ starts from 0, meaning the first element of the array is at index 0, the second element
is at index 1, and so on.

Unit: 5 - Arrays in C++ 11


DCA1210 : Object-Oriented Programming using C++

Example:

int arr[5] = {1, 3, 5, 7, 9};

cout << arr[3]; // This will print the value at index 3 of the array, which is 7.

In this example, the array arr contains 5 elements. By accessing arr[3], the program prints the value
7, which is the fourth element in the array (remember, indexing starts from 0).

Displaying All Elements of an Array

If you want to display all the elements of a 1D array, you can use a loop to iterate through each element
and print its value. The loop runs from 0 to the size of the array minus one, ensuring that each element
is accessed and displayed in order.

Example:

int arr[5] = {1, 3, 5, 7, 9};

cout << "The array elements are: \n";

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

cout << arr[i] << " ";

The array arr is initialized with 5 elements: {1, 3, 5, 7, 9}. A for loop is used to iterate over the array.
The loop variable i starts at 0 and increments by 1 on each iteration, continuing until i is less than 5
(the size of the array). During each iteration, arr[i] accesses the element at the current index, and cout
prints it followed by a space. The output will be: 1 3 5 7 9

3.1.3 Manipulation of 1D Array Elements


Manipulating elements within a one-dimensional (1D) array involves accessing a specific element by
its index and then updating its value. This allows you to modify the data stored in the array after it
has been initialized.

In the example provided, the program demonstrates how to change the value of a specific element in
the array.

Unit: 5 - Arrays in C++ 12


DCA1210 : Object-Oriented Programming using C++

Example Code:

#include <iostream>

using namespace std;

int main() {

int arr[7] = {10, 20, 30, 40, 55, 60, 70}; // Initialize the array with 7 elements

// Display the 5th element before updating

cout << "5th value of Array Before updation: \n" << arr[4];

// Update the 5th element (index 4) to a new value

arr[4] = 50;

// Display the 5th element after updating

cout << "\n5th value of Array After updation: \n" << arr[4];

return 0;

Declaration of Strings in 1D Array

A one-dimensional (1D) array in C++ can be used not only to store numeric values but also to store
alphabetic values, such as characters. A string in C++ is essentially an array of characters, i.e., you can
declare and initialize a string as a 1D array using the char data type.

Syntax:

char string_name[string_size] = {comma_separated_character_list};

where,

Unit: 5 - Arrays in C++ 13


DCA1210 : Object-Oriented Programming using C++

o Char is the data type used for characters.

o string_name is the name you give to the array (i.e., the string).

o string_size is the maximum number of characters the string can hold, including the null
terminator \0.

o comma_separated_character_list is a list of characters enclosed in curly braces {}.

Example:

char str[20] = {"Hello World"};

cout << str;

The array str is declared as a character array that can hold up to 20 characters. The array is initialized
with the string "Hello World". In C++, strings are automatically null-terminated, meaning a special
character \0 is added to the end of the string to indicate where the string ends.

3.2 Multidimensional Arrays


Multidimensional arrays can be described as “arrays of arrays”. The size of an array can be
represented using a subscript. If an array has two subscripts we can call it a two dimensional array.
If an array has more than one subscript, we can call it a multi-dimensional array. Multi-dimensional
arrays contain as many indices as required, if it is not limited to two indices (i.e., two dimensions).

3.2.1 Two- Dimensional arrays


The simplest form of the multidimensional array is the two-dimensional array. A Two-Dimensional
(2D) Array is a data structure that organizes elements in a matrix-like format consisting of rows and
columns. This structure allows data to be stored and accessed in a tabular form, making it suitable for
representing complex datasets like grids, tables, and matrices.

In many real-world scenarios, data is naturally organized in a tabular format, where it is arranged in
rows and columns. This structure is often seen in various types of data such as spreadsheets, matrices,
tables, and more. Some common examples include:

• Spreadsheet Data: A spreadsheet contains data arranged in rows and columns, making it easy
to manage and analyze large datasets.

Unit: 5 - Arrays in C++ 14


DCA1210 : Object-Oriented Programming using C++

• Periodic Table: The elements in the periodic table are organized in a grid-like structure,
where each element can be located based on its row and column.

• Multiplication Table: A multiplication table shows the product of numbers in a grid format,
with rows representing one factor and columns representing the other.

• Movie Ratings: Ratings given by different users for various movies can be stored in a table
where rows represent users and columns represent movies.

• Employee Salaries: In a company, employee information such as names, job titles, and
salaries might be organized in a table format, with each row representing an employee and
each column representing a specific piece of information.

To efficiently store and manage such tabular data, a Two-Dimensional Array (2D Array) is required.

A 2D Array allows data to be stored in a grid-like structure, where each element is identified by two
indices—one for the row and one for the column.

Syntax:

data_type array_name[x][y];

where,

o data_type specifies the type of data that the array will hold (e.g., int, float, char, etc.).

o array_name is the name you choose for the array.

o X is the number of rows in the array.

o Y is the number of columns in the array.

Example 1:

int matrix[3][4];

where,

o int is the data type, meaning each element in the array will be an integer.

o matrix is the name of the 2D array.

o 3 specifies that the array has 3 rows.

o 4 specifies that the array has 4 columns.

Unit: 5 - Arrays in C++ 15


DCA1210 : Object-Oriented Programming using C++

Example 2:

Imagine storing the grades of students in different subjects in a school. Each row could represent a
student, and each column could represent a subject. A 2D Array would allow you to store and access
this data in a way that mirrors the logical structure of the information.

int grades[3][4] = {

{85, 90, 78, 92}, // Grades for Student 1

{88, 76, 93, 85}, // Grades for Student 2

{91, 89, 82, 87} // Grades for Student 3

};

Advantages of Using a 2D Array:

1. Structured Data Storage: A 2D Array provides a natural way to store and organize data that
is inherently tabular, ensuring that related data is kept together in an intuitive format.

2. Efficient Access: With 2D Arrays, accessing any specific element in the table is
straightforward. By using two indices, you can directly access the data at any row and column
intersection, making retrieval and manipulation of data efficient.

3. Data Representation: Many real-world datasets and mathematical constructs (such as


matrices) are naturally two-dimensional. A 2D Array allows for a direct representation of such
data structures in a programming environment, simplifying the coding process.

4. Memory Management: 2D Arrays are stored in contiguous memory locations, which can
make operations like traversing the array or applying algorithms (e.g., sorting, searching)
more efficient.

The following program accepts two, 2x3 matrices from the user and adds the two matrices.

//matrix.cpp

#include <iostream> // Use iostream instead of iostream.h

using namespace std;

Unit: 5 - Arrays in C++ 16


DCA1210 : Object-Oriented Programming using C++

int main() { // main should return int, not void

int a[2][3], b[2][3], c[2][3];

int i, j;

cout << "Enter the elements for the first 2x3 matrix:\n";

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {

cin >> a[i][j];

cout << "Enter the elements for the second 2x3 matrix:\n";

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {

cin >> b[i][j];

c[i][j] = a[i][j] + b[i][j];

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

for (i = 0; i < 2; i++) {

for (j = 0; j < 3; j++) {

cout << c[i][j] << " "; // Use proper quotes

cout << endl;

return 0; // return 0 in main

Unit: 5 - Arrays in C++ 17


DCA1210 : Object-Oriented Programming using C++

Multi-dimensional arrays can also be initialized by specifying row by row values. Every row elements
are initialized by enclosing them in separate flower brackets.

int a[2][2] = {{ 3,4},{ 2, 7}}

In the example given above, elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively.

3.2.2 N- Dimensional arrays


Multi-dimensional arrays contain more than one index. If an array has ‘n’ indices, then it is called an
‘n-dimensional array’. The general syntax of an n-dimensional array is:

Datatype name [Size1] [Size2]... [SizeN];

Example: if an array has 3 indices then it is called a 3-dimensional array.

Int P[2][3][4]

Unit: 5 - Arrays in C++ 18


DCA1210 : Object-Oriented Programming using C++

4. ARRAY OPERATIONS

Arrays are one of the most commonly used data structures, and various operations can be performed
on them.

4.1 Declaration and definition of arrays


Like variable declaration, arrays are also declared along with the data type. Array declaration
reserves space for a number of elements. The declaration of array contains the name of the array
along with square brackets. Inside the square brackets specify size of the array. Int x[10];

An integer array x is declared with the size 10. The size is used to indicate the number of elements an
array can store. The elements of an array can be accessed using the array name followed by index
number within square brackets, i.e. x[0], x[1] to till x[9]. The index of an array starts with 0 and the
last index number of an array is size-1.

4.2 Initialization of an array


To specify values to an array, we should explicitly initialize specific values. You can specify
declaration and initialization of the array in a single statement. Initialization of an array can be
defined in the following form:

int a[5]= { 3, 6, 9,12,15}

The number of values between braces { } are not more than the size of the array. Declaration and
initialization of the array can be done in a single statement. Then the above example can also be
declared and initialized as follows:

Int a[]= { 3, 6, 9,12,15}

Supposing you declare the array and initialize values to it using the same statement, you can omit the
size of the array.

The following program shows how you can add values of array to find the sum of elements of the
array.

Unit: 5 - Arrays in C++ 19


DCA1210 : Object-Oriented Programming using C++

#include <iostream> // Correct header file

using namespace std; // Using standard namespace

int main() { // Return type should be int

int i, sum = 0;

int a[10] = {1, 2, 3, 4, 6, 9, 2, 8, 5, 10}; // Array with size 10

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

sum = sum + a[i];

// Display the result

cout << "\nSum of values of an array is = " << sum << endl;

return 0; // Return statement

Output

Sum of values of an array is = 50

=== Code Execution Successful ===

Another interesting aspect of the array is that all the elements in the arrays are allotted consecutive
spaces in the memory by the operating system.

The following program sorts an array. Here nested for loops are used to enable this.

#include <iostream>

using namespace std;

int main() {

int a[10], temp;

Unit: 5 - Arrays in C++ 20


DCA1210 : Object-Oriented Programming using C++

// Input 10 elements into the array

cout << "Enter 10 elements for the array:" << endl;

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

cin >> a[i];

// Bubble sort to sort the array in ascending order

for (int j = 0; j < 9; j++) {

for (int i = 0; i < 9 - j; i++) {

if (a[i] > a[i + 1]) {

temp = a[i];

a[i] = a[i + 1];

a[i + 1] = temp;

// Output the sorted array

cout << "Array after sorting is:" << endl;

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

cout << a[i] << endl;

return 0;

Unit: 5 - Arrays in C++ 21


DCA1210 : Object-Oriented Programming using C++

All the elements in the array should be initialized. Every data should be separated by a comma and
all the elements enclosed within flower brackets are as shown below:

int data[5] = {3,5,7,4,9};

In the above initialization, data[0] is initialized to 3, and data[1] is initialized to 5 and so on..

3 data[0]

5 data[1]

7 data[2]

4 data[3]

9 data[4]

Unit: 5 - Arrays in C++ 22


DCA1210 : Object-Oriented Programming using C++

4.3 Modifying Array Elements in C++


Once an array is declared and initialized, elements can be modified by directly assigning new values
to specific indices within the array. Array elements are accessed using their index, and you can modify
the value stored at any index.

Syntax

array_name[index] = new_value;

where,

o array_name is the name of the array.

o Index is the position of the element you want to modify (indexing starts from 0).

o new_value is the value you want to assign to the element at the specified index.

Example:

#include <iostream>

using namespace std;

int main() {

// Initialize an array with 5 elements

int arr[5] = {10, 20, 30, 40, 50};

// Display the original array

cout << "Original array: ";

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

cout << arr[i] << " ";

cout << endl;

Unit: 5 - Arrays in C++ 23


DCA1210 : Object-Oriented Programming using C++

// Modify the third element (index 2)

arr[2] = 100;

// Modify the first element (index 0)

arr[0] = 500;

// Display the modified array

cout << "Modified array: ";

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

cout << arr[i] << " ";

cout << endl;

return 0;

4.4 To find the maximum element


Finds and prints the maximum value in a small array of three elements.

#include <iostream>

using namespace std;

Unit: 5 - Arrays in C++ 24


DCA1210 : Object-Oriented Programming using C++

int main() {

int arr[3] = {10, 25, 15}; // Array with 3 elements

int max = arr[0]; // Initialize max with the first element of the array

// Loop through the array starting from the second element

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

if (arr[i] > max) { // Compare each element with the current max

max = arr[i]; // If a larger element is found, update max

cout << "Max: " << max << endl; // Print the maximum value

return 0;

The above code is used to find the maximum element in an array. Initially, the variable max is set to
the first element of the array, assuming that this element is the maximum. The program then enters
a loop, starting from the second element, and iterates through each subsequent element in the array.
For each element, it compares the current element to the value stored in max. If the current element
is greater than max, the program updates max to this new value. This process continues until all
elements in the array have been compared. After the loop finishes, the variable max holds the largest
value found in the array, which is then printed to the console. This program is straightforward and
effective, ensuring that the largest number in the array is identified and outputted.

Unit: 5 - Arrays in C++ 25


DCA1210 : Object-Oriented Programming using C++

4.5 Reversing an Array


Reversing an array means rearranging the elements of the array in the opposite order. For instance,
if the original array is [1, 2, 3], reversing it would result in [3, 2, 1]. The provided code snippet
demonstrates how to reverse an array in C++ using a loop and a temporary variable.

The idea is to swap elements from the start of the array with elements from the end, moving towards
the center. This is done using a loop that runs from the start of the array to the middle (n/2). In each
iteration of the loop, the current element from the start (arr[i]) is swapped with the corresponding
element from the end (arr[n - i - 1]). A temporary variable temp is used to hold the value of arr[i]
during the swap process. This ensures that the original value is not lost when the swap occurs.

This loop effectively reverses the array because it systematically swaps each pair of elements from
the two ends of the array. Once the loop completes, the array will be fully reversed.

#include <iostream>

using namespace std;

int main() {

int arr[] = {1, 2, 3}; // Example array

int n = 3; // Size of the array

// Loop to reverse the array

for (int i = 0; i < n / 2; i++) {

int temp = arr[i]; // Store the current element in temp

arr[i] = arr[n - i - 1]; // Swap the current element with the corresponding element from the end

arr[n - i - 1] = temp; // Assign the value from temp to the corresponding element from the end

// Print the reversed array

Unit: 5 - Arrays in C++ 26


DCA1210 : Object-Oriented Programming using C++

cout << "Reversed array: ";

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

cout << arr[i] << " ";

cout << endl;

return 0;

4.6 Searching for an element


Searching for an element in an array involves checking each element in the array to see if it matches
a specific value (referred to as the "target"). The process begins by setting up a loop that iterates
through all the elements of the array. For each element, the program checks if it is equal to the target
value. If a match is found, a flag (in this case, the found variable) is set to true, and the loop is
terminated early using the break statement. After the loop, the program checks the value of the found
flag to determine whether the target element was found in the array.

Code to search a target key:

#include <iostream>

using namespace std;

Unit: 5 - Arrays in C++ 27


DCA1210 : Object-Oriented Programming using C++

int main() {

int arr[] = {10, 20, 30}; // Example array

int target = 20; // Element to search for

bool found = false; // Flag to indicate if the element is found

// Loop through the array to search for the target element

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

if (arr[i] == target) { // Check if current element matches the target

found = true; // Set the flag to true if found

break; // Exit the loop as the element is found

// Display whether the element was found or not

if (found) {

cout << "Element found!" << endl;

} else {

cout << "Element not found!" << endl;

return 0;

Unit: 5 - Arrays in C++ 28


DCA1210 : Object-Oriented Programming using C++

4.7 Sorting an Array


Sorting an array is the process of arranging the elements in a specific order, either ascending or
descending. Bubble Sort is a simple and well-known sorting algorithm that repeatedly steps through
the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is
repeated until the entire array is sorted.

Example: Code to sort an array

#include <iostream>

using namespace std;

int main() {

int arr[] = {30, 10, 20}; // Example array

// Bubble Sort algorithm to sort the array in ascending order

for (int i = 0; i < 3 - 1; i++) { // Outer loop

for (int j = 0; j < 3 - i - 1; j++) { // Inner loop

if (arr[j] > arr[j + 1]) { // Compare adjacent elements

int temp = arr[j]; // Swap if they are in the wrong order

arr[j] = arr[j + 1];

arr[j + 1] = temp;

Unit: 5 - Arrays in C++ 29


DCA1210 : Object-Oriented Programming using C++

// Display the sorted array

cout << "Sorted array: ";

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

cout << arr[i] << " ";

cout << endl;

return 0;

Unit: 5 - Arrays in C++ 30


DCA1210 : Object-Oriented Programming using C++

5. SUMMARY

In this unit, learners have studied the fundamentals of arrays, starting with the introduction to arrays,
their declaration, and definition. They explored how arrays are initialized and how to effectively use
them for storing and organizing data. Different types of arrays, including one-dimensional and
multidimensional arrays, were also covered. Learners learned how to input elements into a one-
dimensional array, access and manipulate these elements, and perform essential operations such as
finding, modifying, and updating data within the array. They also examined multidimensional arrays,
with a specific focus on two-dimensional and N-dimensional arrays, which allow for more complex
data structures.

Learners also studied various array operations. This included how to declare, define, and initialize
arrays in C++, and how to modify array elements once they have been initialized. Learners practiced
key techniques such as finding the maximum element in an array, reversing the order of array
elements, searching for a specific element within an array, and sorting arrays either in ascending or
descending order.

Unit: 5 - Arrays in C++ 31


DCA1210 : Object-Oriented Programming using C++

6. GLOSSARY

A collection of elements, all of the same data type, stored in contiguous


Array -
memory locations and accessible using indices.

A single value or item stored in an array. Each element can be accessed


Element -
via an index.

A number used to access an element in an array, starting from 0 for the


Index -
first element.

One-Dimensional A linear collection of elements stored in a single row, where each


-
Array (1D Array) element is accessed using a single index.

A collection of elements organized in rows and columns, often visualized


Two-Dimensional
- as a matrix. Accessed using two indices, one for the row and one for the
Array (2D Array)
column.
An array with more than one dimension, where elements are accessed
Multidimensional
- using multiple indices (e.g., 3D arrays with indices for rows, columns,
Array
and depth).

Declaration of an The process of defining an array's name, data type, and size in a C++
-
Array program.

Initialization of an
- Assigning values to the elements of an array at the time of its declaration.
Array

An array whose size is determined at compile-time and cannot change


Static Array -
during the program's execution.

An array whose size can be determined at runtime using dynamic


Dynamic Array -
memory allocation, often using pointers and the new keyword in C++.

Unit: 5 - Arrays in C++ 32


DCA1210 : Object-Oriented Programming using C++

7. SELF-ASSESSMENT QUESTIONS

Multiple Choice Questions:


1 Which data structure allows storing multiple elements of the same type under one name?
a) Pointer
b) Array
c) Structure
d) Queue
2 Which of the following is the correct way to declare an array in C++?
a) int arr[5];
b) arr[5] int;
c) array int arr[5];
d) int[5] arr;
3 Which of the following cannot be an array element type?
a) int
b) float
c) char
d) void
4 What is the size of the array int arr[10];?
a) 20 bytes
b) 10 bytes
c) Depends on the compiler
d) 40 bytes
5 What will be the output of the following code?
int arr[3] = {10, 20, 30};
cout << arr[2];
a) 10
b) 20
c) 30
d) Compile-time error
Fill in the blanks:

Unit: 5 - Arrays in C++ 33


DCA1210 : Object-Oriented Programming using C++

6 The syntax to declare a two-dimensional array is ________.


7 Array size must be specified during the ________ of an array.
Correct the Statement:
8 Array elements are accessed using a pointer in C++.
True or False Questions:
9 In C++, arrays are stored in contiguous memory locations.
10 You cannot declare an array of objects in C++.

Unit: 5 - Arrays in C++ 34


DCA1210 : Object-Oriented Programming using C++

8. TERMINAL QUESTIONS

1. Explain how to declare and initialize an array in C++ with an example.


2. What is a one-dimensional array, and how can you input and access elements in a 1D array?
Provide a sample C++ program.
3. Describe the key differences between one-dimensional and two-dimensional arrays with an
example of a 2D array in C++.
4. Write a C++ program to input 5 elements into a 1D array and display them.
5. Explain how elements of a one-dimensional array are accessed. Write a simple program to
demonstrate this.
6. Write a C++ program to find the maximum element in a 1D array of integers.
7. How can you reverse the elements in a one-dimensional array? Provide a step-by-step
explanation.
8. Describe the types of arrays and their differences, including examples for one-dimensional and
multidimensional arrays.
9. Write a C++ program to declare a 2D array to store a 3x3 matrix, input the elements, and display
the matrix. Explain how you can access elements from a 2D array.
10. Write a C++ program to sort an array of integers using the bubble sort technique. Explain the
algorithm used in the program.

Unit: 5 - Arrays in C++ 35


DCA1210 : Object-Oriented Programming using C++

9. ANSWERS
Self-Assessment Questions
Answer 1: Refer to section 5.1

Answer 2: Refer to section 5.2.1

Answer 3: Refer to section 5.2.2.1

Answer 4: Refer to section 5.2.1.1

Answer 5: Refer to section 5.2.1.2

Answer 6: Refer to section 5.3.4

Answer 7: Refer to section 5.3.5

Answer 8: Refer to section 5.2

Answer 9: Refer to section 5.2.2.1

Answer 10: Refer to section 5.3.7

Terminal Questions Answers


Answer 1:

#include <iostream>

using namespace std;

int main() {

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

cout << arr[5];

return 0;

Answer 2:

#include <iostream>

using namespace std;

Unit: 5 - Arrays in C++ 36


DCA1210 : Object-Oriented Programming using C++

int main() {

int arr[3];

arr[0] = 5;

arr[1] = 10;

arr[2] = "twenty";

return 0;

Answer 3:

#include <iostream>

using namespace std;

int main() {

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

cout << arr[3];

return 0;

Answer 4:

#include <iostream>

using namespace std;

int main() {

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

cout << arr[2];

return 0;

Unit: 5 - Arrays in C++ 37


DCA1210 : Object-Oriented Programming using C++

Answer 5:

#include <iostream>

using namespace std;

int main() {

int arr[3];

arr[1] = 10;

arr[2] = 20;

cout << arr[0];

return 0;

Answer 6:

Error: Array index out of bounds. arr[5] is invalid because the highest index for a 5-element array is
4.

Correction: cout << arr[4];

Answer 7:

Error: Mismatched data type. The array is of type int, but "twenty" is a string.

Correction: Replace "twenty" with 20.

Answer 8:

Error: Index out of bounds. The valid indices for arr[3] are 0, 1, and 2. arr[3] is out of bounds.

Correction: cout << arr[2];

Answer 9:

Error: The array is declared with 3 elements, but only 2 values are initialized. arr[2] is uninitialized.

Correction: Initialize all 3 elements, e.g., int arr[3] = {1, 2, 3};

Unit: 5 - Arrays in C++ 38


DCA1210 : Object-Oriented Programming using C++

Answer 10:

Error: arr[0] is accessed without being initialized, leading to unpredictable output.

Correction: Initialize arr[0], e.g., arr[0] = 5;

Unit: 5 - Arrays in C++ 39


DCA1210 : Object-Oriented Programming using C++

12. To Calculate Relative Frequency, count occurrences of each colour (Red, Blue, Green, Yellow)
10. REFERENCES
and calculate the percentage of each colour relative to the total number of responses. You can derive

• Learning C++ Programming Concepts by Tickoo Sham, Pearson Education India.

• C++ for Programmers by Paul Deitel, Harvey M. Deitel, Pearson Education.

• C++ Primer Plus by Stephen Prata, Addison-Wesley Professional.

• Object-oriented Programming with C++ - Sixth Edition by E. Balagurusamy. Tata McGraw-Hill


Education.

Unit: 5 - Arrays in C++ 40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy