Object - Oriented Programming Using C++.
Object - Oriented Programming Using C++.
DCA1210
OBJECT - ORIENTED PROGRAMMING
USING
Unit: 1 - Introduction to Object-Oriented ProgrammingC++ 1
DCA1210: Object-Oriented Programming using C++
Unit – 1
Introduction to Object-Oriented
Programming
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 -
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.
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.
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
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.
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.
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
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.
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
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.
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.
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.
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
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.
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.
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.
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
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.
o Eliminating Redundant Code: Using inheritance, we can reuse existing code, which reduces the
need to write the same code multiple times.
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.
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.
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.
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.
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.
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
10 Inheritance in OOP allows objects to inherit properties from multiple classes at the same
time.
Fill in the Blanks:
8. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective
A function that is defined within a class and can operate on the data
Method -
contained within an object of that class.
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
int main()
{ // Execution starts at main() function
int a, b, c;
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.
int main() {
// Declare variables for length, width, and area
double length, width, area;
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
message indicating the result. The program concludes with a return 0; statement, signaling successful
execution.
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.
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.
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 :-
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
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.
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++
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.2 Comments - -
2.5 Namespace - -
3.1 Variables1 - -
16 - 18
3.2 Input Operator 2 -
12 Terminal Questions - - 36
13 Answers - - 37
14 References - - 38
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.
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.
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.
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.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.
// This is an example of
// C++ program to illustrate
// Some of its features
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++".
the iostream.h header file should be used. This is relevant for older compilers that have not been
updated to support the newer standards.
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.
Header File
Contents and Purpose New Version
(Old Version)
Header File
Contents and Purpose New Version
(Old Version)
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.
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 Output:
Hello from firstNamespace!
Hello from secondNamespace!
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.
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.
return 0;
}
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.
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.
For example:
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:
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:
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.
#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()
{
person p;
p.getdata();
p.display();
return 0;
}
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).
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
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.
• 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.
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.
• 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.
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.
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.
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:
The development and execution of C++ programs using Visual C++ under Windows are briefly
discussed in Appendix C (not provided in the image).
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).
The datatypes supported in C++ are listed below with size and range:
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:
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.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:
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).
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.
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
11. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective
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.
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.
Fundamental Data
Basic data types provided by C++, such as int, char, float, and double.
Types
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.
Preprocessor Instructions in C++ that are processed by the preprocessor before the
Directive actual compilation starts, such as #include and #define.
The concept in OOP of bundling the data and the methods that operate on
Encapsulation -
the data within a single unit, a class.
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
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.
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++
TABLE OF CONTENTS
Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4-5
1.1 Objectives - -
2 Operators - -
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.
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++.
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.
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.
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.
The Table 1.2 illustrates relational operators with example. In example consider X=10 and Y=20.
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.
Example:
………..
………..
{
Int x=10;
………..
………..
}
…………
…………
{
Int x=1;
……….
……….
}
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.
The figure 1 illustrates the concept of block nesting in C++. Here, you see two blocks, Block 1 and
Block 2.
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.)
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.
:: variable-name
#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
return 0;
}
Output:
We are in inner block
k = 20
m = 30
::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.
The new operator is used to create objects of any given type, following the general syntax:
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;
*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:
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.
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:
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.
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 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.
………
………
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
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
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.
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
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.
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.
Example:
int globalVar = 0;
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.
• 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;
}
Example:
class MyClass {
public:
int myNumber;
void myFunction() {
// Code to be executed
}
};
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.
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.
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.
During compilation, if there are any errors, they will be listed by the compiler.
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.
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.
‘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
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).
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.
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)
{
if (condition 2)
{
Statement1;
Statement2;
}
else if (condition3)
{
Statement3;
}
else
Statement 4;
}
STUDY NOTE
&& is the AND operator whereas || is the OR operator.
Multiple conditions can be checked using logical && operator (AND) and || operator (OR).
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.
int main()
{
int studentmarks = 80;
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;
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.
int main() {
char x;
float num1, num2;
Output:
Select an operator either + or - or * or /
+
Enter two operands: 2 3
2+3=5
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.
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;
#include <iostream>
using namespace std;
int main() {
int i = 1, total = 0;
while (i < 10) {
total = total + i;
i++;
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++;
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.
Exit (integer)
Here the integer value return to operating system (OS) while terminating program.
#include <iostream>
#include <cstdlib> // for exit()
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;
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.
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.
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:
6 Conditional control statements like if and switch allow a program to make decisions based on
conditions.
Fill in the Blanks:
8 In C++, the ____ manipulator is used to insert a line break in the output.
7. GLOSSARY
Financial Management is concerned with the procurement of the least cost funds, and its effective
Relational Operators that compare two values and return a boolean result, such as
-
Operators greater than (>), less than (<), equal to (==), and not equal to (!=).
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
Memory
Operators in C++ used to dynamically allocate and deallocate memory,
Management -
specifically new and delete.
Operators
A manipulator that sets the width of the next output field, useful for
setw Manipulator
formatting text in columns.
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.
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.
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
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.
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++
TABLE OF CONTENTS
Fig No /
SL SAQ / Page
Topic Table /
No Activity No
Graph
1 Introduction - -
4-5
1.1 Objectives - -
2 Type Conversion - -
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++.
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.
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).
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.
int main()
{
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
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).
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".
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);
• 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.
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.
• 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;
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.
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);
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).
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.
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.
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.
#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] << ", ";
}
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.
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.
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;
The following program creates a dynamic array, and finds the sum of array elements:
#include <iostream>
using namespace std;
int main()
{
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.
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;
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:
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.
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
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.
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.
To handle allocation failures gracefully, you can check if the allocation was successful:
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
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.
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.
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
d) Returns NULL
a) 10
b) 10.0
c) 0
d) undefined
Fill in the Blanks:
15 What is the keyword used to prevent exceptions on failure during memory allocation?
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 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 process of accessing the value stored at the memory address held by
Dereferencing -
a pointer using the * operator.
Dynamic Memory The process of allocating memory during runtime using operators like
-
Allocation new and delete.
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.
std::bad_alloc - An exception thrown when the new operator fails to allocate memory.
An operator used to free memory allocated for arrays using the new[]
delete[] Operator -
operator.
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
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];
}
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
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.
Output:
Memory allocation succeeded.
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.
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
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.
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
1 Introduction - -
5
1.1 Objectives - -
2 Introduction to arrays - - 6
3 Types of Arrays - -
4 Array Operations - -
5 Summary - - 31
6 Glossary - - 32
8 Terminal Questions - - 35
9 Answers - - 36-39
10 References - - 40
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
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:
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.
3. TYPES OF ARRAYS
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:
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,
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:
where,
o data_type: Specifies the type of data the array will hold, such as int, float, char, etc.
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.
Example:
where,
o int is the data type, meaning the array will store integers.
o {10, 20, 30, 40, 50} is the list of values assigned to the array elements.
Here,
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:
• Direct Initialization
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:
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.
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.
Example:
#include <iostream>
int main() {
int num[5];
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.
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.
Example:
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).
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:
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
In the example provided, the program demonstrates how to change the value of a specific element in
the array.
Example Code:
#include <iostream>
int main() {
int arr[7] = {10, 20, 30, 40, 55, 60, 70}; // Initialize the array with 7 elements
cout << "5th value of Array Before updation: \n" << arr[4];
arr[4] = 50;
cout << "\n5th value of Array After updation: \n" << arr[4];
return 0;
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:
where,
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.
Example:
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.
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.
• 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.).
Example 1:
int matrix[3][4];
where,
o int is the data type, meaning each element in the array will be an integer.
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] = {
};
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.
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
int i, j;
cout << "Enter the elements for the first 2x3 matrix:\n";
cout << "Enter the elements for the second 2x3 matrix:\n";
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.
In the example given above, elements 3 and 4 will be initialized to a[0][0] and a[0][1] respectively.
Int P[2][3][4]
4. ARRAY OPERATIONS
Arrays are one of the most commonly used data structures, and various operations can be performed
on them.
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.
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:
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.
int i, sum = 0;
cout << "\nSum of values of an array is = " << sum << endl;
Output
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>
int main() {
temp = a[i];
a[i + 1] = temp;
return 0;
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:
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]
Syntax
array_name[index] = new_value;
where,
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>
int main() {
arr[2] = 100;
arr[0] = 500;
return 0;
#include <iostream>
int main() {
int max = arr[0]; // Initialize max with the first element of the array
if (arr[i] > max) { // Compare each element with the current 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.
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>
int main() {
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
return 0;
#include <iostream>
int main() {
if (found) {
} else {
return 0;
#include <iostream>
int main() {
arr[j + 1] = temp;
return 0;
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.
6. GLOSSARY
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
7. SELF-ASSESSMENT QUESTIONS
8. TERMINAL QUESTIONS
9. ANSWERS
Self-Assessment Questions
Answer 1: Refer to section 5.1
#include <iostream>
int main() {
return 0;
Answer 2:
#include <iostream>
int main() {
int arr[3];
arr[0] = 5;
arr[1] = 10;
arr[2] = "twenty";
return 0;
Answer 3:
#include <iostream>
int main() {
return 0;
Answer 4:
#include <iostream>
int main() {
return 0;
Answer 5:
#include <iostream>
int main() {
int arr[3];
arr[1] = 10;
arr[2] = 20;
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.
Answer 7:
Error: Mismatched data type. The array is of type int, but "twenty" is a string.
Answer 8:
Error: Index out of bounds. The valid indices for arr[3] are 0, 1, and 2. arr[3] is out of bounds.
Answer 9:
Error: The array is declared with 3 elements, but only 2 values are initialized. arr[2] is uninitialized.
Answer 10:
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