Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
14 views48 pages

Problem Solving Using C++ - Unit 1

Uploaded by

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

Problem Solving Using C++ - Unit 1

Uploaded by

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

Problem Solving Using C++ Unit 1

I Semester BCA
Problem Solving using C++
Course Code: CAM12T Course Title: Problem Solving using C++

Course Credits: 03 (3-0-0) Hours/Week: 03

Total Contact Hours: 44 Formative Assessment Marks: 20

Exam Marks: 80 Exam Duration: 03

Course Outcomes (COs):


On successful completion of this course, students will be able to:
1. Understand the fundamental concepts and benefits of Object-Oriented Programming (OOP) and
how it differs from Procedure-Oriented Programming paradigms.
2. Interpret and apply C++ syntax and structure, including input-output statements, keywords,
identifiers, constants, variables, data types, operators, expressions and file handling to create
basic programs and solve problems.
3. Describe the control structures, functions, and different parameter passing methods and write
programs to solve problems.
4. Demonstrate the concepts of classes and objects , access specifiers, constructors, destructors,
and OOP features like polymorphism, inheritance with the help of programs.

Course Contents

Unit-1
Introduction to Programming: Program development life cycle, Introduction to
Procedure Oriented Programming and Object-Oriented Programming (OOP)
paradigms, basic concepts of OOP, benefits and applications of OOP.
Introduction to C++: Overview of C++, Structure of C++ Program, Input-Output 11Hours
statements, Keywords, Identifiers, Constants, Variables, Data types, Operators,
Types of operators, Expressions, Precedence of Operators, Type Conversion,
Storage classes.
Unit-2

Control statements: Selection And Iteration Statements, Loop Control Statements.


Modular Programming: Functions and Its Types, Recursion, Functions with
11Hours
Default Arguments, Inline Functions, Function Overloading, Call by Value and
Reference, Math Library Functions.

GM – MIT Degree College, MITM Campus, Mysore 1


Problem Solving Using C++ Unit 1

Unit-3
Derived Data Types: Arrays, Array Types, Strings, String Manipulation
Functions, Pointers, Pointer Arithmetic.
Managing Console, I/O Operations: C++ Stream, C++ Stream Classes,
Unformatted I/O Operations, Formatted Console I/O Operations, Managing Output
11Hours
withManipulators.
User Defined Data Type: Class Definition, Instance Variables, Member Methods,
Accessing Members, Access specifiers, this pointer, Friend Function,
Constructors,Types of Constructors, Destructor.
Unit-4
Polymorphism: Operator Overloading, Rules for Operator Overloading,
Overloading Unary and Binary Operators.
Inheritance: Inheritance, Types of Inheritance, Virtual Functions and Abstract
Classes. 11Hours
File Handling: Introduction To Files and File Handling, File Opening Modes, Classes
For File Stream Operations, File I/O Operations (Opening, Reading, Writing,
Append And Closing).

Reference Books:
1. Object-Oriented Programming With C++, By M. T. Somashekara, D. S. Guru, H.
S. Nagendraswamy, K. S. Manjunatha, PHI Learning Pvt. Ltd.

2. Object-Oriented Programming With C++, By E Balaguruswamy, Tata McGraw-Hill


Publicationm Company Ltd.

3. The C++ Programming Language, By Stroustroup, Bjarne, Addison Wesley.

4. How To Solve It by Computer - R G Dromey, Prentice-Hall International

GM – MIT Degree College, MITM Campus, Mysore 2


Problem Solving Using C++ Unit 1

UNIT - 01

Introduction to Programming: Program development life cycle, Introduction to Procedure Oriented


Programming and Object-Oriented Programming (OOP) paradigms, basic concepts of OOP, benefits and
applications of OOP.

Introduction to C++: Overview of C++, Structure of C++ Program, Input-Output statements, Keywords,
Identifiers, Constants, Variables, Data types, Operators, Types of operators, Expressions, Precedence of
Operators, Type Conversion, Storage classes.

Introduction to Programming

 Programming is the process of creating a set of instructions that a computer can follow to perform
specific tasks.
 Programming refers to a technological process for telling a computer which tasks to perform in order to
solve problems.
 It can be considered collaboration between humans and computers, in which humans create instructions for
a computer to follow (code) in a language computers can understand.
 It involves writing code in a programming language to solve problems, automate tasks, or create
software applications.
Example: If you want a computer to calculate the sum of two numbers, programming involves writing
the steps (instructions) that tell the computer how to do this calculation.

Some key terms:

1. Program: A program is a complete set of instructions written in a programming language that tells
the computer how to perform a specific task. It can be something simple, like adding two numbers, or
something complex, like a video game.

Example: A calculator app on your phone is a program. It takes input from the user (numbers and
operations), processes that input (performs the calculations), and then displays the result.

2. Programming Language: A programming language is a formal language used to write the


instructions (programs) that a computer can understand and execute. Programming languages have their
own syntax and rules that programmers must follow.

GM – MIT Degree College, MITM Campus, Mysore 3


Problem Solving Using C++ Unit 1

Example: Some programming languages include Python, C, C++, Java, and JavaScript. Each of these
languages has its own unique way of writing instructions, but they all serve the same purpose: to
communicate with the computer.

3. Instructions: Instructions are the individual steps or commands that make up a program. These are
the specific actions that the computer is told to perform, such as adding numbers, storing data, or
displaying text on the screen.

Example: In a program, an instruction might be something like cout<< ―Hello World"; which tells the
computer to display the text "Hello, World!" on the screen.

4. Software: Software is a collection of programs and data that work together to perform specific tasks
on a computer. It can be anything from operating systems like Windows or macOS to applications like
Microsoft Word, web browsers, or games.

Example: Microsoft Word is a piece of software that allows you to write, edit, and format documents. It
consists of multiple programs that handle different tasks, like opening files, saving your work, and
checking spelling.

Recap:

 Programming is the act of creating a program.


 Program is a set of instructions written in a programming language.
 Programming language is the tool used to write those instructions.
 Instructions are the individual steps that tell the computer what to do.
 Software is the end product, a collection of programs that performs useful tasks on your computer.

Types of programming languages

While hundreds of programming languages (if not thousands) exist, and there are many ways to classify
them, they typically can be grouped into five main categories:

1. Procedural programming languages


2. Functional programming languages
3. Object-oriented programming languages
4. Scripting languages
5. Logic programming languages

GM – MIT Degree College, MITM Campus, Mysore 4


Problem Solving Using C++ Unit 1

1. Procedural programming languages


A procedural language follows a sequence of statements or commands in order to achieve a
desired output. Each series of steps is called a procedure, and a program written in one of these
languages will have one or more procedures within it. Common examples of procedural languages
include:
 C and C++

 Java

 Pascal

 BASIC

2. Functional programming languages


Rather than focusing on the execution of statements, functional languages focus on the output of
mathematical functions and evaluations. Each function–a reusable module of code–performs a specific
task and returns a result. The result will vary depending on what data you input into the function. Some
popular functional programming languages include:
 Scala
 Erlang
 Haskell
 Elixir
 F#

3. Object-oriented programming languages (OOP)


This type of language treats a program as a group of objects composed of data and program
elements, known as attributes and methods. Objects can be reused within a program or in other
programs. This makes it a popular language type for complex programs, as code is easier to reuse and
scale. Some common object-oriented languages include:
 Java
 Python
 PHP
 C++
 Ruby

GM – MIT Degree College, MITM Campus, Mysore 5


Problem Solving Using C++ Unit 1

4. Scripting languages
Programmers use scripting languages to automate repetitive tasks, manage dynamic web content, or
supportprocesses in larger applications. Some common scripting languages include:
 PHP
 Ruby
 Python
 bash
 Perl
 Node.js

5. Logic programming languages


Instead of telling a computer what to do, a logic programming language expresses a series of facts
and rulesto instruct the computer on how to make decisions. Some examples of logic languages include:
 Prolog
 Absys
 Datalog
 Alma-0

Program Development Life Cycle (PDLC)

The Program Development Life Cycle (PDLC) is a step-by-step process used by developers to
create, test, and maintain software programs. It ensures that software is developed systematically and
efficiently, meeting the requirements and delivering a high-quality product.

It provides an organized plan for breaking down the task of program development into
manageable chunks, each of which must be completed before moving on to the next phase.

Stages/Steps involved in the Program Development Life Cycle (PDLC) are:


1. Problem Definition
This is the initial stage where the problem or the task that the program will solve is clearly
defined. It involves understanding the problem by working with stakeholders to gather all the necessary
information and exact requirements for the program. Next, the program goals are defined, outlining the
specific objectives the software must achieve. Once the goals are clear, the inputs and outputs are
identified, specifying the data the program will need to process and what it will produce. Finally, any
constraints and assumptions are considered, including limitations the program must operate within or
specific rules it needs to follow.
GM – MIT Degree College, MITM Campus, Mysore 6
Problem Solving Using C++ Unit 1

Steps involved:

 Understand the problem: The developer or team works with stakeholders (e.g., users, business owners)
to understand the exact requirements. For example, if you're building software for an online store, you
need to understand what features the store needs (like managing products, processing orders, etc.).
 Define program goals: Clearly outline what the software is supposed to achieve. For instance, the goal
could be to allow users to browse and purchase products, or to automate stock management.
 Identify inputs and outputs: Determine what data the program will receive (input) and what it should
produce (output). For example, in a billing system, the input could be item details and customer info, and
the output would be a generated invoice.
 Constraints and assumptions: Identify any limitations or rules the program needs to follow. For
example, the system might need to handle a certain number of users or transactions per day.

2. Program design and Analysis

Program design starts by focusing on the main goal the program needs to achieve and then
breaking it down into smaller, manageable parts. This method is called top-bottom design or
modular programming. First, you identify the main task or activity the program must perform. Then,
you divide this main task into smaller sections called modules. Each module handles a specific part of
the program's work. To plan how each module will work, programmers create a simple diagram or
plan using design tools to show how the module will complete its assigned task. And also we
determine the requirements like variables, functions, etc. to solve the problem. That means we gather
the required resources to solve the problem defined in the problem definition phase. We also
determine the bounds of the solution.
Depending on the module, people use different types of program design tools. The five major
ones are algorithms, structure charts, flowcharts, decision tables, and pseudocode.

 Algorithms: An algorithm is a step-by-step procedure used to solve a problem in the easiest way
possible. An algorithm is an exact list of instructions and can be found in everyday life, not just in
software engineering.
 Structure charts: A structure chart looks at the top-down design of the program and breaks it into the
smallest functional modules. It also describes each module‘s function and sub-function in detail.
 Flowcharts: A flowchart is a diagram showing the logic of the program. It can also be considered a
pictorial representation of an algorithm. Each step of the algorithm is represented in the form of various
shapes of boxes, with the logical flow indicated by interconnecting arrows.

GM – MIT Degree College, MITM Campus, Mysore 7


Problem Solving Using C++ Unit 1

 Decision tables: A decision table is a visual representation that specifies which actions to do based on
given conditions. It is divided into four parts by two horizontal and two vertical lines. Software
engineers and product teams use it to settle different combinations of inputs with their corresponding
outputs.
 Pseudocode: It‘s informative text or annotations written in plain English and used to represent an
implementation of algorithms. Since it has no syntax, it can‘t be compiled or interpreted by a computer.

3. Coding (Implementing) the program


Once the program is designed, the next step is to translate that design into a working program by
writing code in a programming language like C++, Java, or Python. This is where the plan from the
design stage is turned into an actual software application.

Steps involved:

 Write the code: Developers write the program‘s source code based on the design plan. They translate
algorithms, flowcharts, and pseudocode into the actual programming language.
 Follow coding standards: It‘s important to follow best practices and coding standards to ensure the
code is readable, maintainable, and efficient. This includes using meaningful variable names, comments,
and consistent formatting.
 Modular coding: The program is usually written in modules or functions. Each module handles a
specific task, making it easier to debug and test.
 Error handling: Include mechanisms to deal with potential errors (e.g., input validation, exception
handling) to prevent the program from crashing during use.

4. Testing and Debugging the program


After coding, the program needs to be thoroughly tested to ensure it works as expected. Testing
identifies any errors (bugs) that need to be fixed before the software is released.

Debugging: This is the process of finding and fixing errors (bugs) in the program. Common types of
bugs include:

 Syntax errors: Mistakes in the code that prevent it from running.


 Logic errors: Errors in the logic that cause the program to produce incorrect results.
 Runtime errors: Errors that occur when the program is running (e.g., dividing by zero, accessing an
invalid memory location).

GM – MIT Degree College, MITM Campus, Mysore 8


Problem Solving Using C++ Unit 1

5. Documenting the program


Documentation is the process of writing manuals and guides that explain how the program
works. There are two types of documentation: technical documentation and user documentation.

Types of documentation:

 Technical documentation: This is for developers and includes details about the program‘s code,
structure, algorithms, and database design. It helps future developers understand how the program was
built so they can maintain or modify it if needed.
 User documentation: This is for the end-users, explaining how to install, operate, and troubleshoot the
software. It‘s often written in a simple language and includes step-by-step instructions with examples or
screenshots.

6. Deploying and Maintaining the program


In the final phase, the program is deployed (installed) at the user‘s site. Here also, the program
is kept under watch till the user gives a green signal to it. Even after the software is completed, it
needs to be maintained and evaluated regularly. Maintenance involves making improvements, fixing
bugs that were discovered after the release, and updating the software to meet new requirements or to
ensure compatibility with new technologies.

Types of maintenance:

 Corrective maintenance: Fixing errors or bugs that were not caught during testing.
 Adaptive maintenance: Updating the software to work with new environments (e.g., new operating
systems or hardware).
 Perfective maintenance: Improving the performance or adding new features based on user feedback or
new business needs.
 Preventive maintenance: Making changes to improve the software‘s future maintainability and
reliability, even if no current problems exist.

Example for PDLC: Developing a library management system for a school. This is a system that
helps manage the books, track borrowing and returning, and keep records of students and books.

1. Problem Definition: The library needs software to manage books, keep track of which student
borrowed which book, and show when the books are due for return. The goal is to reduce manual work
and improve accuracy in record-keeping.

GM – MIT Degree College, MITM Campus, Mysore 9


Problem Solving Using C++ Unit 1

2. Program Design: The program is broken into different tasks: book cataloging, student records,
borrowing/returning books, and overdue reminders. Each task will be handled by a separate module. For
instance, the borrowing module will track which student borrowed which book.

3. Coding: The programmer writes the code to implement the design. The book cataloging module will
allow the librarian to add, update, or remove books from the system. The borrowing module will update
the system when a student borrows or returns a book.

4. Testing and Debugging: The library management system is tested to ensure it works properly. For
example, when a book is borrowed, the system should show that it's no longer available for others until it
is returned.

5. Documentation: User documentation is created for the librarian, explaining how to use the system to
add books, register students, and manage borrowings. Technical documentation is also written for future
developers.

6. Maintenance: After the system is in use, updates might be needed, like adding a new feature for e-
books or fixing a bug that prevents correct tracking of overdue books.

Procedure Oriented Programming and Object-Oriented Programming Paradigm

A programming paradigm is a method or style of programming that defines a set of principles,


techniques, and patterns for structuring code to solve problems on a computer.

Procedure Oriented Programming (POP)


Procedure-Oriented Programming (POP) is a programming paradigm that utilizes the use of
procedures or functions to operate on data. In POP, the focus is on defining functions that perform
operations on data, which is usually stored in global variables. This paradigm organizes code into
procedures that can be executed sequentially to accomplish tasks.
It is based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out. During a
program‘s execution, any given procedure might be called at any point, including by other procedures
or itself.
POP is straightforward and effective for small to medium-sized programs, but it can become
challenging to manage as programs grow larger due to the reliance on global data and the lack of
inherent mechanisms for data encapsulation and modularity.
GM – MIT Degree College, MITM Campus, Mysore 10
Problem Solving Using C++ Unit 1

Features of Procedural Programming:

 Predefined functions: A predefined function is typically an instruction identified by a name.


Usually, the predefined functions are built into higher-level programming languages (Links to an
external site.) Links to an external site, but they are derived from the library or the registry, rather
than the program. One example of a pre-defined function is ‗charAt()‘, which searches for a character
position in a string.

 Local Variable: A local variable is a variable that is declared in the main structure of a method and
is limited to the local scope it is given. The local variable can only be used in the method it is defined
in, and if it were to be used outside the defined method, the code will cease to work.
 Global Variable: A global variable is a variable which is declared outside every other function
defined in the code. Due to this, global variables can be used in all functions, unlike a local variable.
 Modularity: Modularity is when two dissimilar systems have two different tasks at hand but are
grouped together to conclude a larger task first. Every group of systems then would have its owntasks
finished one after the other until all tasks are complete.
 Parameter Passing: Parameter Passing is a mechanism used to pass parameters to functions,
subroutines or procedures. Parameter Passing can be done through ‗pass by value‘, ‗pass by
reference‘, ‗pass by result‘, ‗pass by value-result‘ and ‗pass by the name‘.

Advantages and Disadvantages of Procedural Oriented Programming


Advantages:
 Procedural Programming is excellent for general-purpose programming
 The coded simplicity along with ease of implementation of compilers and interpreters
 A large variety of books and online course material available on tested algorithms, making it easier to
learn along the way
 The source code is portable, therefore, it can be used to target a different CPU as well
 The code can be reused in different parts of the program, without the need to copy it
 Through Procedural Programming technique, the memory requirement also reduces.
 The program flow can be tracked easily

Disadvantages:

 The program code is harder to write when Procedural Programming is employed


 The Procedural code is often not reusable, which may pose the need to recreate the code if is needed
to use in another application

GM – MIT Degree College, MITM Campus, Mysore 11


Problem Solving Using C++ Unit 1

 Difficult to relate with real-world objects


 The importance is given to the operation rather than the data, which might pose issues in some data-
sensitive cases
 The data is exposed to the whole program, making it not so much security friendly

Languages used in Procedural Programming:


FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.

Example: Adding two numbers using POP


#include <iostream.h>
#include<conio.h>

// Function to add two numbers  It is a comment, it will not execute. It is for our reference
int adding(int a, int b)
{
return a + b;
}

void main()
{
int num1 = 5, num2 = 10, result;
clrscr();

result = adding(num1, num2);

cout << "Sum= " << result << endl;

getch();
}

Object-Oriented Programming(OOP)
Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of methods. In
object-oriented programming, computer programs are designed using the concept of objects that
interact with the real world. Object-oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also determine their types.

Features of Object Oriented Programming paradigm

 Programs are divided into simple elements referred to as object


 Focus is on properties and functions rather than procedure.
 Data is hidden from external functions.
 Functions operate on the properties of an object.
 Objects may communicate with each other through a function called messaging.
GM – MIT Degree College, MITM Campus, Mysore 12
Problem Solving Using C++ Unit 1

 Follow the bottom-up approach in oop design

Languages used in Object-Oriented Programming:


Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart, Swift, Scala.
Example: Adding two numbers using OOP
#include <iostream.h>
#include<conio.h>

// Class to perform addition


class Adder
{
public:
// Method to add two numbers
int add(int a, int b)
{
return a + b;
}
};
void main()
{
// Adder is a class name and add is a object name
Adder add;

int num1 = 5, num2 = 10, result;


clrscr();

result = adder.add(num1, num2);

cout << "Sum: " << result << endl;

getch();
}

Differences between Procedure


Oriented Programming (POP) and Object Oriented Programming (OOP)

Procedural Oriented Programming Object-Oriented Programming


In procedural programming, the program is In object-oriented programming, the program

GM – MIT Degree College, MITM Campus, Mysore 13


Problem Solving Using C++ Unit 1

divided into small parts called functions. is divided into small parts called objects.
Procedural programming follows a top-down Object-oriented programming follows
approach. a bottom-up approach.
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
In procedural programming, there is no concept In object-oriented programming, the concept of
of data hiding and inheritance. data hiding and inheritance is used.
In procedural programming, the function is In object-oriented programming, data is more
more important than the data. important than function.
Procedural programming is used for designing Object-oriented programming is used for
medium-sized programs. designing large and complex programs.
Code reusability absent in procedural Code reusability present in object-oriented
programming, programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.

Basic Concepts of Object Oriented Programming (OOP)

1. Objects
2. Classes
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing

1. Objects
 Objects are the basic run-time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program must handle.
 Objects are basic building blocks for designing programs.
 It is called instance of class (occurrence /copy of class).
 Object is a collection of data member and member functions..
GM – MIT Degree College, MITM Campus, Mysore 14
Problem Solving Using C++ Unit 1

 Each object is identified by unique name and it must be a member of particular class.
 Object takes the space in the memory.

2. Class
 A class is a blueprint/template for creating objects.
 Class is a way of grouping of objects having similar characteristics.
In other words, a group of objects that share common properties for data part and some
program part are collectively called as class.
 Once the class is created, any number of objects can be created for that particular class.
 Classes are user defined datatype.
 When the class is created, no memory is allocated. But when it is instantiated then the memory is
allocated. Instantiation is the process of creating a real object from a class.

Data members are the data variables that are declared inside a class and hold the state of the class. They
represent the attributes or properties of the class.

Member functions are the functions used to manipulate these variables and that are declared inside a
class and operate on the data members of that class. They define the behavior or actions that the class
can perform.

Together these data members and member functions defines the properties and behavior of the
objects in a Class.

In the below example, breed, size, age, color are data members. Eat(), sleep(), sit(), run() are member
functions.

GM – MIT Degree College, MITM Campus, Mysore 15


Problem Solving Using C++ Unit 1

3. Data Abstraction
 Abstraction is about hiding complex implementation details and showing only the essential features of
an object.
 It hides the unwanted information and represents only the necessary information.
 In other words, it refers to the act of
representing essential features without
including the back ground details or
explanations.
Example: Imagine you are using an ATM
machine to check your account balance. The
ATM provides a user-friendly interface with
options like "Check Balance," "Withdraw
Money," and "Deposit Funds." You interact
with the ATM through this interface without
needing to understand the complex processes
behind the scenes.

In terms of data abstraction, the ATM


represents an abstract view of your bank
account. You only see and interact with the essential functionalities that you need, such as entering your

GM – MIT Degree College, MITM Campus, Mysore 16


Problem Solving Using C++ Unit 1

PIN and selecting options from the menu. The underlying details—such as how the ATM communicates
with the bank's servers, how the transactions are processed, and how data is securely transmitted—are
hidden from you. This abstraction simplifies your experience by providing a straightforward and
consistent interface, while the complexities of data handling and security are managed by the ATM's
internal systems.

By hiding these complex details and showing only the necessary options, the ATM machine
demonstrates the principle of data abstraction. It allows you to perform financial transactions efficiently
without needing to understand the intricate workings behind the scenes.

4. Data Encapsulation
 Encapsulation is about bundling/ wrapping up of the data (properties) and methods (functions) that
operate on the data into a single unit called a class.
 The data is not accessible to the outside world and only those functions which are wrapped in the
class can access it. These functions provide the interface between the objects data and the program.

 For example, you might have a BankAccount class where the balance is private and can only be
accessed or modified through methods like deposit() and withdraw().

5. Inheritance
 Inheritance is the process by which objects of one class acquire the properties
of another class.
 Inheritance allows one class (child class) to inherit properties and methods
from another class (parent class).
 In the concept of inheritance provides the idea of reusablity. This mean that
we can add additional features to an existing class with out modifying it.
 The existed class is called as base class or parent class or super class. The

GM – MIT Degree College, MITM Campus, Mysore 17


Problem Solving Using C++ Unit 1

new class is called as derived class or child class or sub class.

Example: Imagine you have a parent class called Animal that defines basic attributes and methods
common to all animals, such as name and eat(). Now, you want to create a specific type of animal, like a
Dog. Instead of rewriting the code for the common attributes and methods, you create a Dog class that
inherits from the Animal class. The Dog class automatically has the name and eat( ) methods from the
Animal class, but you can also add new attributes, like breed, and methods, like bark( ). This way, the
Dog class extends the functionality of the Animal class by adding its own unique features while reusing
the common functionality provided by its parent class.

6. Polymorphism
 Polymorphism means the ability to take more than one form. An
operation may exhibit different instance.
 The behaviour depends upon the type of data used in the
operation.
 C++ supports operator overloading and function overloading.
o Operator Overloading: The process of making an operator
exhibit different behaviors in different instances is known as
operator overloading.
o Function Overloading: Function overloading is using a single
function name to perform different types of tasks. Polymorphism
is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some
integers, sometimes there are 2 integers, and sometimes there are
3 integers. We can write the Addition Method with the same name
having different parameters, the concerned method will be called
according to parameters.

7. Dynamic binding
 Dynamic binding refers to the linking of a procedure call to the code to the executed in response to
the call.
 Dynamic binding means the code associated with a given procedure call is not known untill the time

GM – MIT Degree College, MITM Campus, Mysore 18


Problem Solving Using C++ Unit 1

of the call at run-time.


 It connects function call with the function definition.
 It is associated with a polymorphic reference depends upon the dynamic type of that reference.
Example: Imagine you have a universal remote control designed to operate various home devices,
such as a TV, DVD player, and sound system. When you press a button on the remote, the action
performed depends on the type of device currently selected. For instance, pressing the "Play" button
will send a signal to the DVD player to start playing a movie, but if the TV is selected, the same
button might change the channel instead.
This process demonstrates dynamic binding in action. When you press the button, the remote
control does not know ahead of time which device will receive the command or what specific action will
be performed. Instead, it determines the appropriate method to invoke at runtime based on the currently
selected device. This decision-making occurs dynamically, allowing the remote to interact with various
devices in a flexible and adaptable manner. Dynamic binding ensures that the correct method is chosen
and executed according to the actual type of device being controlled, even though the exact method to be
invoked is determined only during the runtime of the program.

8. Message Passing
 It is a mechanism that allows objects to communicate and interact with each other by sending messages.
 An object oriented program consists of a set of objects that communicate with each
other.
 A message for an object is a request for execution of a procedure and therefore will invoke a function
(procedure) in the receiving object that generates the desired result. Message passing involves
specifying the name of the object, the name of the function (message) and information to be sent.
Example: Imagine you have a whiteboard in an office where you leave notes(messages) for different
team members. If you write ―Send the report‖ on the board, the team member who handles reports will
see it and act on it. If you write ―Call the client,‖ the person in charge of phone calls will handle that
task. Each team member looks at the note and does what is needed based on the message. This way,
messages are passed to the right person, and they perform the appropriate action.

Benefits of OOP
GM – MIT Degree College, MITM Campus, Mysore 19
Problem Solving Using C++ Unit 1

1. Security (Encapsulation): In OOP, encapsulation is the concept of bundling data (variables) and
methods (functions) that operate on the data into a single unit called a class. This ensures that the data is
protected from being accessed or modified by external functions, enhancing security.

Example: Think of a banking system. Your account balance (data) is private and cannot be directly
changed by anyone. Instead, you can only update it through methods like deposit or withdraw. This
prevents unauthorized access or changes to your account balance.

2. Reusability (Inheritance): Through inheritance, you can create a new class based on an existing
class, inheriting its properties and methods. This saves time and effort because you don‘t need to rewrite
the same code for similar functionalities.

Example: Suppose you have a Vehicle class with properties like wheels, engine, and methods like
start(). You can create a Car class that inherits from Vehicle, and automatically gains these properties
and methods. You can then add specific properties like airbags to the Car class without rewriting the
basic vehicle features.

3. Effective Communication (Message Passing): Objects in OOP communicate with each other
through message passing, which means that they send messages (call methods) to request actions or
share information. This makes the interaction between objects simpler and more structured.

Example: In a messaging app, when you send a message to a friend, your User object might call a
sendMessage() method on your friend's User object. This is a clear and defined way of how objects
communicate in an OOP system.

4. Model Real-World Effectively: OOP allows you to model real-world objects as classes in your
program, creating a direct correspondence between the real world and your software. This makes the
software more intuitive and easier to design.

Example: Consider an e-commerce platform. You can create a Product class, a Customer class, and an
Order class. Each class can have attributes and methods that directly map to the real-world objects and
their behaviors, like a customer adding a product to their cart.

5. Suitable for Developing Complex Software: OOP is ideal for developing complex software systems
because it allows for better management of complexity through features like inheritance, encapsulation,
and polymorphism. These features help in organizing and reducing the complexity of large codebases.

GM – MIT Degree College, MITM Campus, Mysore 20


Problem Solving Using C++ Unit 1

Example: In large software applications like enterprise resource planning (ERP) systems, different
modules like inventory, finance, and human resources can be modeled as separate classes, with shared
properties inherited from a base class. This reduces redundancy and keeps the system organized.

6. Easy to Upgrade (Bottom-Up Approach): OOP often employs a bottom-up approach in system
development, meaning you start by creating small, manageable objects or classes and then combine them
to build more complex systems. This makes it easier to upgrade or expand the system over time.

Example: If you're developing a gaming application, you might first create basic classes like Character,
Weapon, and Environment. Later, you can add new features or classes like MagicCharacter or
AdvancedWeapon without disrupting the existing system.

7. Additional Power for Operator (Operator Overloading): OOP allows operators to work differently
based on the type of data they are working with through a concept called operator overloading. This
gives more flexibility and power to operators in the program.

Example: In a graphics software, you might have a Point class representing coordinates. You can
overload the + operator to allow adding two Point objects together, resulting in a new point that
represents their sum. For example, Point(1, 2) + Point(3, 4) might result in Point(4, 6).

8. Easy to Decompose Complicated Work: OOP makes it easier to break down complex problems into
smaller, more manageable parts by focusing on objects rather than functions. This modular approach
simplifies the development and maintenance process.

Example: In a simulation of a traffic system, you could break down the system into objects like Car,
TrafficLight, and Pedestrian. Each object handles its own behavior, making the overall system easier to
develop and manage.

Applications of OOP

GM – MIT Degree College, MITM Campus, Mysore 21


Problem Solving Using C++ Unit 1

1. Object-Oriented Database: Object-oriented databases store data in the form of objects, similar to
how data is represented in OOP. This allows for a more natural and direct mapping between objects in a
program and the data in the database.

Example: A content management system (CMS) for a website may use an object-oriented database to
store and retrieve web pages, user data, and multimedia content, where each entity is represented as an
object.

2. Computer Graphics: OOP is widely used in computer graphics for managing and manipulating
complex graphical elements. Objects can represent graphical entities like shapes, colors, and
transformations.

Example: In video game development, characters, environments, and even effects like lighting and
shadows are implemented as objects, making it easier to manage and render them efficiently.

3. Real-Time Systems: Real-time systems require immediate or timely responses to inputs. OOP helps
in modeling these systems where each real-time task can be represented as an object with specific
behaviors.

Example: An anti-lock braking system (ABS) in a car uses real-time processing to prevent wheel lock
during braking. Each component of the system, like the sensors and actuators, can be represented as
objects, interacting in real-time to ensure safety.

4. Parallel Programming: OOP supports parallel programming by allowing objects to operate


concurrently, making it easier to manage parallel processes.

Example: In a modern web server, multiple client requests can be handled simultaneously. Each request
can be treated as an object running in parallel threads, allowing efficient and concurrent processing.

5. System Programs: System programs like compilers, interpreters, and operating systems often use
OOP to manage the complexity of these large systems. OOP helps in modularizing the components of
the system.

Example: The Java Virtual Machine (JVM) uses OOP principles to manage memory, interpret bytecode,
and execute programs, making it easier to port Java applications across different platforms.

GM – MIT Degree College, MITM Campus, Mysore 22


Problem Solving Using C++ Unit 1

6. Artificial Intelligence (AI) and Expert Systems: OOP allows the modeling of complex AI systems
where each component of the AI can be represented as an object with its own data and behavior.

Example: In a chess-playing AI, different elements like the board, pieces, and game rules are
represented as objects, allowing the AI to evaluate and make moves based on the current state of the
game.

7. CAD/CAM Software: Computer-Aided Design (CAD) and Computer-Aided Manufacturing (CAM)


software use OOP to model real-world objects that need to be designed or manufactured.

Example: In designing a car using CAD software, different parts of the car like the engine, body, and
wheels are treated as objects. These objects can be modified and assembled in the software, reflecting
changes in real-time.

8. Neural Networks:Neural networks in machine learning are often implemented using OOP principles,
where each neuron or layer in the network is represented as an object.

Example: In a facial recognition system, each layer of the neural network can be an object that processes
the image data, extracting features and making predictions based on learned patterns.

Disadvantages of Object-Oriented Programming:


1. Steep learning curve: The thought process involved in object-oriented programming may not be
natural for some people, and it can take time to get used to it. It is complex to create programs based
on interaction of objects. Some of the key programming techniques, such as inheritance and polymorphism,
can be challenging to comprehend initially.
2. Larger program size: Object-oriented programs typically involve more lines of code than
procedural programs.
3. Slower programs: Object-oriented programs are typically slower than procedure-based programs, as
they typically require more instructions to be executed.
4. Increased complexity: OOP's emphasis on modularity and code organization can make larger projects more
challenging to understand and maintain.
5. Not suitable for all types of problems: There are problems that lend themselves well to functional-
programming style, logic-programming style, or procedure-based programming style, and applying
object-oriented programming in those situations will not result in efficient programs.

GM – MIT Degree College, MITM Campus, Mysore 23


Problem Solving Using C++ Unit 1

Introduction to C++

 In 1980s, the C language was playing a dominant role. But when the software size started increasing, it
could not scale up to meet the requirements. Then, C++ was developed by Bjarne Stroustrup at AT
and T Bell Labs in the early 1980’s (1979) as an enhancement to the C language and originally named
C with Classes but later it was renamed C++ in 1983.
 C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-
level language features.
 C++ was developed as an extension of C, and both languages have almost the same syntax. The main
difference between C and C++ is that C++ support classes and objects, while C does not. C++ is a
superset of C.
 The C programming language was developed by Dennis Ritchie at Bell Labs in the early 1970s. It was
initially designed to create system software for the Unix operating system, which was also being
developed at Bell Labs.
Features of C++:

1. Object-Oriented Programming: Supports concepts like classes, objects, inheritance, polymorphism,


encapsulation, and abstraction.
2. Rich Standard Library (STL): Offers a collection of generic classes and functions, including
algorithms, iterators, and data structures.
3. Case-sensitive: It is clear that C++ is a case-sensitive programming language. For example, cin is used
to take input from the input stream. But if the ―Cin‖ won‘t work. Other languages like HTML and
MySQL are not case-sensitive languages.
4. Memory Management: Provides fine control over memory allocation with features like pointers,
dynamic allocation, and deallocation.
5. Operator Overloading: Allows operators to be redefined for user-defined data types, providing
intuitive use of custom types.
6. Multiple Inheritance: Supports inheriting properties from more than one class, which is not available in
many other languages.
7. Low-Level Manipulation: Offers direct manipulation of hardware and system resources, making it
suitable for system programming.

Advantages of C++
GM – MIT Degree College, MITM Campus, Mysore 24
Problem Solving Using C++ Unit 1

1. Performance: C++ is a compiled language, which means that its code is compiled into machine-
readable code, making it one of the fastest programming languages.
2. Object-Oriented Programming: C++ supports object-oriented programming, which makes it easier to
write and maintain large, complex applications.
3. Standard Template Library (STL): The STL provides a wide range of algorithms and data structures
for working with data, making it easier to write efficient and effective code.
4. Portability: C++ code can be compiled on different platforms with minimal changes, making it a
portable language.
5. Flexibility: C++ supports both low-level (close to hardware) and high-level programming, making it
suitable for a wide range of applications.

Disadvantages of C++:

1. Complexity: C++ has a steep learning curve, especially for beginners, due to its complex syntax,
features, and concepts like pointers, memory management, and multiple inheritance.
2. Verbose Syntax: C++ has a verbose syntax, which can make code longer and more difficult to read and
maintain.
3. Error-Prone: C++ provides low-level access to system resources, which can lead to subtle errors that
are difficult to detect and fix.
4. Long Compilation Times: The compilation process in C++ can be slow, especially for large programs,
due to the complexity of the language and its features.

Applications of C++:

1. System Software: Operating systems like Windows, Linux, and macOS use C++ for their development.
2. Game Development: C++ is widely used in game development due to its high performance and ability
to manage system resources efficiently. Game engines like Unreal Engine are built using C++.
3. Database Management Systems: Databases like MySQL and PostgreSQL have components written in
C++.
4. GUI Applications: Desktop applications with graphical user interfaces, such as Adobe Photoshop, are
often developed using C++.
5. Compilers: Many compilers and interpreters for other programming languages (including C++ itself)
are written in C++.
6. Web Browsers: C++ is used in developing web browsers like Google Chrome and Mozilla Firefox,
particularly for performance-critical parts like rendering engines.

GM – MIT Degree College, MITM Campus, Mysore 25


Problem Solving Using C++ Unit 1

The Structure of C++ Program

documentation
include files
classes declaration and definition
macros definition
global variables declaration

int main(void)
{
Local variables
Statements
Return 0;
}

 Documentation consists of comment lines mentioning the name, input, output etc. For example, //
program to swap two numbers. The comments lines are ignored during compilation.

There are two types of comments they are:

1. Single line comments: Single line comments should be written in this form.
// abc
Comment should be written only in single line.
2. Multiline comments: Multiline comments should be written in this form
.
/* Write a program to swap two numbers Using
temporary variable */

Comments can be written in more than one line.

 Include files is used to specify the files which are to be included as the part of the program. C++
compilers are provided with a standard library, which consist of a large number of commonly used
built in functions. In order to use these functions, we need to include some files as the part of our
program. These files are generally called as header files.

For eg. iostream.h, conio.h

The preprocessor directive #include is used for this purpose.

Example: #include<iostream.h>
GM – MIT Degree College, MITM Campus, Mysore 26
Problem Solving Using C++ Unit 1

 Classes declaration and definition is to declare and define the classes that are used by the program.
 Macros definition is to assign symbolic names to constants and define macros. The preprocessor
directive #define is used for this purpose.
Example: #define PI 3.14

NOTE: Commands written by using # are called pre-processor directives. Before C program is
compiled by the compiler, source program is processed by Pre-processor directives. As the name
suggests, Preprocessors are programs that process our source code before compilation.

All of these preprocessor directives begin with a ‗#‘ (hash) symbol. Examples of some
preprocessor directives are: #include, #define, etc.

 Global variables are those which are required to be accessed by all the functions defined after their
declaration. So, the variables declared before the main() can be accessed by all the functions which
follow their declaration.

All the above parts are optional. They can be used only when they are required. They can appear in
any order. Then comes the function main(). Every C++ program will have a one main(), this is where the
execution of a program starts from and ends with.

The Opening brace { of the main( ) marks the physical beginning of the program and the closing
brace } marks the physical end of the program. The statements enclosed within the opening brace and
the closing brace form the body of the main( ). It consists of two parts: 1. Local Variables declaration,
where all the variables, which are accessed only by the main( ) are declared and
2. Statements, which includes the executable statements.

After the closing brace of the main( ), user defined functions ,if any, can be defined. The word int
before the main( ) indicates that the main( ) returns an int value to its caller, the underlying operating
system and the word void within the parentheses indicate that the main( ) does not require any inputs
from the calling programs.

GM – MIT Degree College, MITM Campus, Mysore 27


Problem Solving Using C++ Unit 1

Example C++ Programme:

1) // Program to display "Hello World"


#include <iostream.h>
Output: Hello World
#include<conio.h>
void main()
{
cout << "Hello World";
getch( );
}

2) // Program to add 2 numbers


#include <iostream.h>
#include <conio.h>
void main()
{
int a,b,sum;

cout << "Enter the values for a and b: ‖;cin>>a>>b;


Output:
sum=a+b; Enter the values for a and b: 20 40
cout<<‖The Sum is: ―<<sum; The Sum is: 60
getch( );
}

GM – MIT Degree College, MITM Campus, Mysore 28


Problem Solving Using C++ Unit 1

The input and output statements

In C++ input and output are performed in the form of a sequence of bytes or more commonly
knownas streams.

 Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the
main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device
(display screen) then this process is called output.

Header files available in C++ for Input/Output operations are:

1. iostream: iostream stands for standard input-output stream. This header file contains definitions of
objects like cin, cout, cerr, etc.

2. iomanip: iomanip stands for input-output manipulators. The methods declared in these files areused
for manipulating streams. This file contains definitions of setw, setprecision, etc.

3. fstream: This header file mainly describes the file stream. This header file is used to handle the data
being read from a file as input or data being written into the file as output.
 Standard output stream (cout):

The name cout stands for ‗character output‘ or ‗console output‘. Usually the standard output device is
the display screen. The C++ cout statement is the instance of the ostream class. It is used to produce
output on the standard output device which is usually the display screen. The data needed to be
displayed on the screen is inserted in the standard output stream (cout) using the insertion operator
(<<).

Example:

#include <iostream.h>
#include <conio.h>

void main()
{
cout << " Hello World";
}
Output: Hello World

 Standard input stream (cin): The name cin stands for ‗character input‘ or ‗console input‘. Usually
the input device in a computer is the keyboard. C++ cin statement is the instance of the class
istream and is used toread input from the standard input device which is usually a keyboard.

The extraction operator (>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.

GM – MIT Degree College, MITM Campus, Mysore 29


Problem Solving Using C++ Unit 1

Example:

#include <iostream.h>
#include <conio.h>
Output:
void main()
{ Enter your age: 18
int age; Your age is: 18
cout << "Enter your age:";
cin >> age;
cout << "\nYour age is: " << age;
getch( );
}

NOTE: cout and cin are generally understood to refer to "Console Output" and "Console Input"
because they work specifically with the console (terminal) for displaying output and receiving input in
C++. The word "console" is more commonly used in modern interpretations.

Historically, some early references or resources referred to cout as "Character Output" and cin as
"Character Input" due to their handling of textual characters (strings, numbers, etc.) when performing
input and output operations.

Keywords

keywords are those words of C++ which have predefined meaning assigned by the C + + languoage.
They should not be used for any other purpose other than the purpose for which they are meant. The
keywords are also called reserved words.

Some of the keywords are as follows: int, float, class, return, void, char, double, private, public,
protected etc

There are 95 keywords reserved in C++. Some of the main Keywords are:
break try catch char class const continue
default delete auto else friend for float
long new operator private protected public return
short sizeof static this typedef enum throw
mutable struct case register switch and or
namespace static_cast goto not xor bool do
double int unsigned void virtual union while

Identifiers

The identifier is one which is used for elements like variables constants are in its functions
names etc. In C++, entities like variables, functions, classes, or structs must be given unique names within the
GM – MIT Degree College, MITM Campus, Mysore 30
Problem Solving Using C++ Unit 1
program so that they can be uniquely identified. The unique names given to these entities are known as
identifiers.

It is recommended to choose valid and relevant names of identifiers to write readable and
maintainable programs. Keywords cannot be used as an identifier because they are reserved words to
do specific tasks.

There are a few rules must be followed while constructing a valid identifiers. They are

 An identifier can have maximum 31 characters. The permissible characters in an identifier include
letters digits and an optional underscore symbol
 It should start with a letter
 Special characters other than underscore or not permitted
 It should not be a keyword. For example, string, int, class, struct, etc.
NOTE: As C++ is a case-sensitive language so identifiers such as ‗first_name‘ and
‗First_name‘ aredifferent entities.

Here are some examples of valid and invalid identifiers in C++:

Valid Invalid Identifiers


Identifiers
_name #name (Cannot start with special character except ‗_‘)
Number89 2num (Cannot start with a digit)
first_name first name (Cannot include space)
_last_name string (Cannot be same as a keyword)
_

Variables : Variables are a name given to identify the specific program elements. It is the basic
unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
 In C++, all the variables must be declared before use.

Rules for declaring variable:

 The name of the variable contains letters, digits, and underscores.


 The name of the variable is case sensitive (ex Arr and arr both are different variables).
 The name of the variable does not contain any whitespace and special characters (ex #,$,%,*, etc).
However, the name must not start with a number.

 All the variable names must begin with a letter of the alphabet or an underscore(_).
GM – MIT Degree College, MITM Campus, Mysore 31
Problem Solving Using C++ Unit 1

 We cannot used C++ keyword (for ex float, double, class) as a variable name.

Valid variables Invalid


variables
Marks 8ab
Number num-88
total Cube‘s
total_marks Total marks
_total and&

Declaration of Variables
All the variables must be declared before they are used in a C++ program. The purpose of declaring
variables is to reserve the amount of memory required for these variables.

// Declaring a single variable:


It is the syntax for declaring a single variable
datatype variable_name;
int a; It is the example for declaring a single variable

// Declaring multiple variables:


data type variable1_name, variable2_name, variable3_name; int
A, B, Sum;
Assigning values to variables
The process of giving values to a variable is called the assignment of values. The assignment operator
―=‖ is used to assign a value to variable.
Syntax: datatype variable_name = value; // at the time of declaration
Variable_name= value; //after declaration
Where,
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable. It is a constant.
Example: int x=0, y;
y=0

C++ Data types:


C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application.

A data type specifies the type of data that a variable an store such as integer,
floating, character etc. Data types specify the size and types of values to be stored.
However, storage representation and machine instructions to manipulate each data type
differ from machine to machine, although C++ instructions are identical on all machines.
GM – MIT Degree College, MITM Campus, Mysore 32
Problem Solving Using C++ Unit 1

All variables use data type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data they can
store. Whenever a variable is defined in C++, the compiler allocates some memory for that
variable based on the data type with which it is declared. Every data type requires a different
amount of memory.

C++ supports the following data types:

1. Primary or Built-in or Fundamental data type


2. Derived data types
3. User-defined data types

Data Types in C++ are mainly divided into 3 Types:

1. Primitive Data Types: These data types are built-in or predefined data types and
can be useddirectly by the user to declare variables. example: int, char, float, bool, etc.
Primitive data types available in C++ are:

 Integer (int)
 Character (char)
 Boolean (bool)
 Floating Point (float)
 Double Floating Point (double)
 Valueless or Void (void)
Size and Range of Primary Data Types:

Data Size in Range


type byte
char 1 -27 to 27-1
int 2 -215 to 215-1
float 4 -231 to 231-1
double 8 -263 to 263-1
void Nil Nil

Modifiers: Modifiers are the keywords in C++ which either increase or decrease the size of basic
data type. Also, it makes the variable to represent only positive or both positive and negative
numbers. It specifies the amount of memory space to be allocated for a variable. Modifiers are
prefixed with basic data types to modify the memory allocated for the variable.
Syntax: modifier_name datatype_name variable_name;
Example: long int x;

There are 5 types of modifiers in C they are:

GM – MIT Degree College, MITM Campus, Mysore 33


Problem Solving Using C++ Unit 1

1. Long: Long is used to increase the size.


2. Short: Short is used to decrease the size.
3. Signed: It specifies the negative or positive representation of a number.
4. Unsigned: It specifies the number as a positive number.
5. Long double: It specifies the number is larger than double.

2. Derived Data Types: Derived data types that are derived from the primitive or built-in data
types. It is an extension of the fundamental data type.

These can be of four types namely:

 Function: A block of code that performs a specific task when it is called.


Example: int add(int a, int b)
{
return a + b;
}

 Array: A collection of elements of the same type stored in adjacent memory.


Example: int arr[3] = {1, 2, 3};

 Pointer: A variable that stores the memory address of another variable.


Example: int x = 10; int* p = &x;

 Reference: An alternative name (nickname) for an existing variable, allowing direct access to its value without
creating a new copy.
Example: int y = 20; int& ref = y;

3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by the user
itself. Like, defining a class in C++ or a structure. Data types created by the programmer that represent real-
world objects or concepts, using a combination of basic data types and operations is called User-Defined Data
Types. C++ provides the following user-defined data types:

 Class: A blueprint for creating objects that can contain both data (attributes) and functions (methods).

Example: class Car


{
public:
string model;
int year;
};
Car myCar;

 Structure: A user-defined data type that groups different data types into a single unit.

GM – MIT Degree College, MITM Campus, Mysore 34


Problem Solving Using C++ Unit 1
Example: struct Person
{
string name;
int age;
};
Person p1;

 Union: A user-defined data type that allows storing different data types in the same memory location,
but only one at a time.

Example: union Data


{
int intValue;
float floatValue;
};
Data d;

 Enumeration: A user-defined type that assigns names to integral constants, making code easier to read.

Example: enum Day { Sunday, Monday, Tuesday };

Day today = Monday;

 typedef: A keyword used to create an alias for an existing data type to simplify code.

Example: typedef unsigned int uint;

uint num = 10;

Operators in C++:
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. It instructs the computer to perform the specified manipulations over the data.
Operators cannot be used in isolation or solely. They have to be used in combination with
either variables or constants or with combination of variables and constants. When used in
combination they are set to form what are called expressions and expression.
An expression in C++ is a combination of variables or constants and operators conforming to
the syntax rules of the language.
The variables are constants used with an operator are called operands. Depending on the
operator used, the expressions are further classified into arithmetic expressions, relational
expressions, logical expressions and so on.
An operator operates the operands. For example, int c = a + b;
Here, ‗+‘ is the addition operator. ‗a‘ and ‗b‘ are the operands that are being ‗added‘.

Operators in C++ can be classified into 3 types:

GM – MIT Degree College, MITM Campus, Mysore 35


Problem Solving Using C++ Unit 1

1. Unary Operators
2. Binary Operators
3. Ternary Operators

1. Unary Operators: A unary operator is an operator in programming that works with only one operand (a
single value or variable). It performs an operation on that single operand and returns a result. It acts upon one
(single) operand.

Symbol Name Description Example


++a or a++
++ Increment Increases value by 1 int a=5,b,c;
b=++a;// b=6, a=6
c=a++; // c=6, a=7
--b or b--
Decreases value by
-- Decrement int a=5,b,c;
1 b=--a;// b=4, a=4
c=a--; // c=4, a=3
+ Unary Plus Indicates positive value +c
- Unary Minus Indicates Negates value -d
Reverses logical
! Logical NOT a = true
state !a == false
int h = 5; // In Binary: 0000 0101
Inverts bits (Bitwise int result = ~h; // Bitwise NOT inverts
~ Bitwise NOT
NOT) the bits: 1111 1010
Output: result = -6 (in decimal)
int x = 10; // Declare an integer variable
Returns address of
& Address-of x
variable int* ptr = &x; // Use the address-of
operator to get the address of x
int a = 20; // Declare an integer variable
int* p = &a; // Declare a pointer p that
stores the address of a
Pointer Accesses value at // Accessing the value using the pointer
*
(Dereference) address int b = *p; // Dereference p to get the
value of a
// Output: b = 20 (the value of a)

2. Binary operators: A binary operator is an operator that requires two operands to perform an
operation. It operates on the two values or variables and returns a result. Most of the operators we use
in programming are binary operators. It acts upon two operands. The binary operators are as follows:
i. Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the operands. For
GM – MIT Degree College, MITM Campus, Mysore 36
Problem Solving Using C++ Unit 1

example, ‗+‘ is used for addition, ‗-‗ is used for subtraction ‗*‘ is used for multiplication, etc. An
arithmetic expression is the one which comprises arithmetic operators and variables or constants.
Symbol Name Description Example

int a = 3, b = 6;
+ Addition Adds two operands
int c = a+b; // c = 9
int a = 9, b = 6;
– Subtracti Subtracts second operand from the first
on operand int c = a-b; // c = 3
int a = 3, b = 6;
* Multiplic Multiplies two operands
int c = a*b; // c = 18
ation
int a = 12, b = 6;
/ Division Divides first operand by the second operand
int c = a/b; // c = 2
int a = 8, b = 6;
% Modulo Returns the remainder an integer division
int c = a%b; // c = 2

ii.Relational Operators: These operators are used for the comparison of the values of two operands.
A relational expression is of the form operand1 operator operand2, where operator is any relational
operator operand1 and operand2 are variables are constants or combination of both, which are being
compared. The value of a relational expression is C + + is 1 or 0. The 1 indicates that the condition is
true and 0 indicates that the condition is false. A relational expression is also called a conditional
expression or a Boolean expression.

Symbol Name Description Example

int a = 3, b = 6;
== Is Equal Checks if both operands are equal
To a==b; // returns false

Checks if first operand is greater than int a = 3, b = 6;


> Greater the second operand a>b; // returns false
Than

Great Checks if first operand is greater than


>=
er or equal to the second operand
Than int a = 3, b = 6;
or a>=b; // returns false
Equal
To

Checks if first operand is lesser than int a = 3, b = 6;


< Less the second operand a<b;// returns true
Than

GM – MIT Degree College, MITM Campus, Mysore 37


Problem Solving Using C++ Unit 1

Less Checks if first operand is lesser than


<=
Than or equal to the second operand int a = 3, b = 6;
or a<=b;// returns true
Equal
To

!= Not Checks if both operands are not equal int a = 3, b = 6;


Equal a!=b;// returns true
To

iii. Logical Operators

These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.

Symbol Name Description Example


int a = 3, b = 6; a&&b;
Returns true only if all the operands are true
&& Logical // returns true
or non-zero
AND
int a = 3, b = 6; a||b;
Returns true if either of the operands is true
|| Logical // returns true
or non-zero
OR
int a = 3;
! Logical Returns true if the operand is false or zero !a;
NOT // returns false
iv.Bitwise Operators

These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.

Symbol Name Description Example

Copies a bit to the evaluated result if it int a = 2, b = 3; (a


& Binary AND
exists in both operands & b); //returns 2

Copies a bit to the evaluated result if it int a = 2, b = 3; (a |


| Binary OR
exists in any of the operand b); //returns 3
Copies the bit to the evaluated result if it
int a = 2, b = 3; (a
^ Binary XOR is present in either of the operands but not
^ b); //returns 1
both
Shifts the value to left by the number of int a = 2, b = 3; (a
<< Left Shift
bits specified by the right operand. << 1); //returns 4
GM – MIT Degree College, MITM Campus, Mysore 38
Problem Solving Using C++ Unit 1

Shifts the value to right by the number of int a = 2, b = 3; (a


>> Right Shift
bits specified by the right operand. >> 1); //returns 1

One‘s int b = 3; (~b);


~ Changes binary digits 1 to 0 and 0 to 1
Complement //returns -4

Truth table:

Binary Representation:

 2: 0000 0010
 3: 0000 0011

Example:
Operation Calculation Result
0000 0010 (a =
2)
Bitwise &
2
AND 0000 0011 (b =
3)
= 0000 0010
2 (0000 0010)
Bitwise
|
OR 1
3 (0000 0011)
= 0000 0011
Left Shift 2 (0000 0010)
<< 1 4
= 0000 0100
Right
2 (0000 0010)
Shift
>> 1 1
= 0000 0001

Bitwise
~ 3 (0000
NOT
0011) -4
= 1111 1100

GM – MIT Degree College, MITM Campus, Mysore 39


Problem Solving Using C++ Unit 1

v.Assignment Operators

These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the
compiler will raise an error. The operators +=, -=, *=, /=, %= are called shorthand operators.
Symbol Name Description Example
Assigns the value on the right to the int a = 2;
= Assignment Operator
variable on the left // a = 2
First adds the current value of the
Add and Assignment Operator variable on left to the value on int a = 2, b = 4;
+=
the right and then assigns the a+=b; // a = 6
result to the variable on the left
First subtracts the value on the right
Subtract and Assignment from the current value of the variable int a = 2, b = 4;
-=
Operator on left and then assign the result to a-=b; // a = -2
the variable on the left
First multiplies the current value of
Multiply and Assignment the variable on left to the value on int a = 2, b = 4;
*=
Operator the right and then assign the result a*=b; // a = 8
to
the variable on the left
First divides the current value of the
Divide and Assignment variable on left by the value on the int a = 4, b = 2;
/=
Operator right and then assign the result to the a /=b; // a = 2
variable on the left

3. Ternary or Conditional Operators (?:) It acts upon three or more operands.


The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If it is
true, then Expression2 gets evaluated and is used as the answer for the expression. If
Expression1 is false, then Expression3 gets evaluated and is used as the answer for the expression.
This operator returns the value based on the condition.

Expression1? Expression2: Expression3

Example:

#include <iostream.h>
#include<conio.h>

void main( )
{
int a = 10, b = 20, max; max = a > b ? a : b;
cout << "Maximum value = " << max;
}

Output:
Maximum value = 20

GM – MIT Degree College, MITM Campus, Mysore 40


Problem Solving Using C++ Unit 1

Other Special Operators

Expressions
An expression is a sequence of operators and their operands, that specifies a computation. An
expression is a combination of operators, constants and variables. An expression may consist of one
or more operands, and zero or more operators to produce a value.
Examples:

1. a+b
2. (a-b)*c
3. 2+(a/b)
4. (a+b) / (x+y)

Precedence of Operators:

Operator precedence determines the grouping of terms in an expression. The associativity of an


operator is a property that determines how operators of the same precedence are grouped in the
absence of parentheses. This affects how an expression is evaluated.

Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator:

For example: x = 7 + 3 * 2;
here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets
multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

GM – MIT Degree College, MITM Campus, Mysore 41


Problem Solving using C++ Unit 1

Type Conversion
Type conversion is the process that converts the predefined data type of one variable
into an appropriate data type. The main idea behind type conversion is to convert two different
data type variables into a single data type to solve mathematical and logical expressions easily
without any data loss. This can be done either implicitly or explicitly, depending on how the
conversion occurs. There are two types of type conversion: Implicit Type Conversion and
Explicit Type Conversion
1. Implicit Type Conversion: The implicit type conversion is the type of conversion done
automatically by the compiler without any human effort. It means an implicit conversion
automatically converts one data type into another type based on some predefined rules of the
C++ compiler. Hence, it is also known as the automatic type conversion. All the data types of
the variables are upgraded to the data type of the variable with largest data type.

GM - MIT Degree College, MITM Campus, Mysore 42


Problem Solving using C++ Unit 1

It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example for implicit type conversion:
#include <iostream.h>
#include<conio.h>
void main( )
{
// assign the integer value
int num1 = 25; Output:
clrscr( );
The value of num1 is: 25
// declare a float variable The value of num2 is: 25
float num2;

// convert int value into float variable using implicit conversion


num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;

getch( );
}

2. Explicit Type Conversion: This process is also called type casting and it is user-defined. Here
the user can typecast the result to make it of a particular data type. Conversions that
require user intervention to change the data type of one variable to another.
In other words, an explicit conversion allows the programmer to manually changes or
typecasts the data type from one variable to another type.
Generally, we force the explicit type conversion to convert data from one type to another
because it does not follow the implicit conversion rule.
The explicit type conversion is divided into two ways:
1. Explicit conversion using the assignment operator
2. Explicit conversion using the cast operator

a. Converting by assignment: This is done by explicitly defining the required type in front of
the expression in parenthesis. This can be also considered as forceful casting.

Example: Program to convert one data type into another using the assignment operator
#include <iostream.h>
#include<conio.h>

void main( )

GM - MIT Degree College, MITM Campus, Mysore 43


Problem Solving using C++ Unit 1

{
// initialize an int variable
int num1 = 25;
clrscr( );
Output:
// declare a float variable
float num2; The value of num1 is: 25
The value of num2 is: 25.0
// convert data type from int to float
num2 = (float) num1;

cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;

getch( );
}

b. Conversion using Cast operator: A Cast operator is an unary operator which forces one
data type to be converted into another data type. C++ supports four types of casting:
i. Static Cast
ii. Dynamic Cast
iii. Const Cast
iv. Reinterpret Cast

i. Static Cast: This is used when you know the type of data at compile time. It's the most basic
cast and is commonly used to convert between related types (like from an integer to a float).
Example:

#include <iostream.h>
#include <conio.h>

void main( )
{
int num = 10; Output:
clrscr( );
Integer: 10 Converted to
float decimal = static_cast<float>(num); // Convert int to float Float: 10.0

cout << "Integer: " << num << endl;


cout << "Converted to Float: " << decimal << endl;

getch( );
}

GM - MIT Degree College, MITM Campus, Mysore 44


Problem Solving using C++ Unit 1

ii. Dynamic Cast: This is used for safely converting pointers or references in an inheritance
hierarchy. It checks at runtime if the conversion is valid (used mainly with polymorphism).
Example:

Base* basePtr = new Derived();


Derived* derivedPtr = dynamic_cast<Derived*>(basePtr); // Convert base pointer to derived

iii. Const Cast: This is used to remove the "const" qualifier from a variable. It allows you to
modify a value that was initially constant.
Example:

const int num = 10;


int* modifiable = const_cast<int*>(&num); // Remove const so you can modify it

iv. Reinterpret Cast: This is a low-level cast used for converting one pointer type to another,
even if they are unrelated. It doesn't check for compatibility, so it's risky.
Example:

int* numPtr = new int(42);


char* charPtr = reinterpret_cast<char*>(numPtr); // Convert int pointer to char pointer

Note: Each cast operator has its own use cases and should be chosen based on the
situation to ensure safe and correct conversions.

Storage Classes:

C++ Storage Classes are used to describe the characteristics of a variable/function. It


determines the lifetime, visibility, default value, and storage location which helps us to trace
the existence of a particular variable during the runtime of a program. Storage class specifiers
are used to specify the storage class for a variable.

Syntax: To specify the storage class for a variable, the following syntax is to be followed:
storage_class var_data_type var_name;

C++ uses 6 storage classes, which are as follows:


i. auto Storage Class
ii. register Storage Class
iii. extern Storage Class
iv. static Storage Class
v. mutable Storage Class
vi. thread_local Storage Class

GM - MIT Degree College, MITM Campus, Mysore 45


Problem Solving using C++ Unit 1

i. auto Storage Class


The auto storage class automatically determines the type of a variable based on its
assigned value. It is typically used when you want the compiler to infer the variable's type. The
scope of auto variables is local to the function in which they are declared, and they only exist
while the function is running. For example, if you write auto x = 10;, the compiler treats x as an
integer. Similarly, auto y = 3.14; is inferred as a double.

Example:
void example()
{
auto x = 10; // 'x' is inferred as an int
auto y = 3.14; // 'y' is inferred as a double
}

ii. register Storage Class


The register storage class is used to suggest that the compiler store a variable in a CPU
register instead of regular memory, which could potentially speed up access. However, this is
just a suggestion, and the compiler may or may not follow it. register variables are also local to
the function and have the same lifetime as other local variables. For example, using register int
count = 0; in a loop can request faster access for that variable.
Example:
void example( )
{
register int count = 0; // 'count' might be stored in a CPU register
for (count = 0; count < 10; count++)
{
// Fast access to 'count'
}
}

GM - MIT Degree College, MITM Campus, Mysore 46


Problem Solving using C++ Unit 1

iii. extern Storage Class


The extern storage class is used to declare a global variable that is defined in another
file. This is useful when you want to share variables across multiple files in a program. An
extern variable is global and has a lifetime for the entire duration of the program. For example,
in one file you can define int num = 100;, and in another file, you can access this variable by
declaring extern int num;.
Example:
// In file1.cpp
int num = 100;

// In file2.cpp
extern int num; // Refers to 'num' in file1.cpp

iv. static Storage Class


The static storage class allows a variable to retain its value across multiple function
calls. Even though it is declared within a function, the value of a static variable is preserved
when the function exits and will be used again when the function is called again. For example,
if static int count = 0; is used inside a function, count will keep its value between function calls.
Example:
void example( )
{
static int count = 0; // 'count' retains its value between calls

count++;

cout << count;


}
v. mutable Storage Class

The mutable storage class allows a member of an object to be modified even if the
object itself is declared as const. Normally, a const object cannot modify its data members, but
a mutable variable is an exception to this rule. For example, a class might have a mutable int x;,
which can be modified within a const function.
Example:
class Test
{
mutable int x;
public:
Test() : x(0)
{

}
void modify( ) const
{
GM - MIT Degree College, MITM Campus, Mysore 47
Problem Solving using C++ Unit 1

x = 10; // Allowed because 'x' is mutable


}
};

vi. thread_local Storage Class


The thread_local storage class ensures that each thread in a multi-threaded program has
its own instance of a variable. This is useful when you want each thread to have its own
separate value for a particular variable, independent of other threads. The variable exists for the
lifetime of the thread, and each thread has its own version of the variable. For example,
declaring thread_local int counter = 0; means each thread will have its own counter.
Example:
thread_local int counter = 0; // Each thread has its own 'counter'
void increment( )
{
counter++; // 'counter' is thread-specific
}

GM - MIT Degree College, MITM Campus, Mysore 48

You might also like