0% found this document useful (0 votes)
7 views93 pages

C++ Programming

The document provides an overview of programming concepts, focusing on Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), including their key features, advantages, and disadvantages. It also discusses the Program Development Life Cycle (PDLC), types of computer languages, and the structure of C++ programs. Additionally, it highlights the differences between POP and OOP, and the applications of OOP in various software development contexts.

Uploaded by

Mohammed Fardeen
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)
7 views93 pages

C++ Programming

The document provides an overview of programming concepts, focusing on Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), including their key features, advantages, and disadvantages. It also discusses the Program Development Life Cycle (PDLC), types of computer languages, and the structure of C++ programs. Additionally, it highlights the differences between POP and OOP, and the applications of OOP in various software development contexts.

Uploaded by

Mohammed Fardeen
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/ 93

Unit-1

Introduction to Programming: Program development life cycle, Introduction to 11


Procedure Oriented Programming and Object-Oriented Programming (OOP) Hours
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.

Fundamental Concepts:
1. Instructions: Instruction is nothing but meaningfully written statement using a programming
language. It is a command to processor to perform an action/operation.

2. Computer Languages:
Language that is used to communicate with the machines to build softwares is called computer
languages.

3. Types of computer languages:


There are 2 types of computer languages they are:
1. Low level language: Low level language is classified as either a machine level language
or assembly level language.

Machine Level Language (MLL): Instructions are represented by the combination of 0‘s
and 1‘s. MLL is called as first generation language. MLL do not need translators since it
can be directly operated on the machines.
E.g., 1001 10101 1101.

Limitations of MLL:
 Lack of readability- programs are difficult to write and read.

Assembly Level Language (ALL): Instructions are represented by using mnemonics or


symbolic codes. ALL is called as second generation language. Usage of symbolic codes
increased the readability of the program.
E.g., ADD a,b.

2. High level language: Instructions are represented in English like language. They are
considered as high level language because it is very much closer to the human languages.
E.g., C, C++, JAVA, C#, PHP etc.

4. Language Translator:
Since machines understand only machine level instructions, the programs written in ALL or HLL
needs to be converted or translated to machine understandable form. This translation is done by
language translators.
Types of Translators:

Page 1 of 27
Compiler: It translates high level language to machine level language whole program at
once.
E.g., Turbo C/C++ compiler.
Interpreter: It translates high level language to machine level language line by line.
E.g., Javascript, PHP interpreter.
Assembler: It translates assembly level language to machine level language.
E.g., Turbo Assembler

5. Software:
Set of programs is called as software. Software can be categorized into 2 types they are:
1. System software.
2. Application software.

System software: Software that manage the operations of the computer. System software
directly interacts with the hardware to make application programs operational.
E.g., Operating system, compilers, assemblers, Disk utility software, network settings
software, etc.

Application software: Software developed to perform a specific task or application.


Application software enable the user to complete tasks such as creating documents,
spreadsheets, databases and publication, sending email, designing graphics, running business
and even playing games.
E.g., MS Word, MS Power point, MS Excel, Billing Software, College management software,
Mobile applications, web browser, media players, anti-virus and MS-office packages, etc.

Program development life cycle:


The Program Development Life Cycle (PDLC) refers to the process involved in creating programs.
It is a structured approach with clearly defined phases to ensure that the program meets user needs
and functions correctly. The main stages in the PDLC are as follows:
1. Problem definition: In this step the problem to be solved is defined clearly without any
confusion or ambiguity.
E.g., A simple calculator which performs arithmetic operations like addition, Subtraction,
multiplication and division.
2. Problem analysis: This is the step in which we identify the inputs, outputs and the
constraints required for the problem.
3. Design: Creating a blueprint or model of the program. We can use algorithms, flowcharts,
structure charts for designing the model.
4. Coding/implementation: In this step the algorithm is transformed into computer readable
instructions, i.e., Program is written using suitable programming language like C++, C, Java,
etc.
5. Testing and debugging: In this stage the program is checked for its correctness. Error and
bugs are identified and eliminated.
6. Documentation: Documents are created to describe the software. There are 2 types of
documents they are:
a. Technical document: these are the document required by developers.

Page 2 of 27
b. User document: These are the documents designed for the sake of user to understand about
the software like user manuals.
7. Maintenance: In this stage any upgradation or modification or errors reported are taken
care.
These stages are often iterative, meaning the process may cycle back to earlier stages if issues or
new requirements arise during development.

Introduction to Procedure Oriented Programming

Procedure-Oriented Programming (POP) is a programming paradigm that emphasizes


functions or procedures to model the solution to the problem. The program is divided into a set of
instructions also called as functions/modules/sub-procedures/method. POP focuses on breaking
down a problem into smaller, manageable tasks (procedures), which can be independently coded
and reused.

Key Features of Procedure-Oriented Programming:

1. Focus on Functions/Procedures:

o POP emphasizes procedures or functions. A large program is divided into smaller,


functional units called procedures (or functions).

o Each procedure performs a specific task and may be called multiple times
throughout the program.

2. Top-Down Approach:

o In POP, the design approach follows a top-down methodology, where the problem
is broken down into smaller sub-problems. The highest level of the problem is
addressed first, then refined into lower levels.

o This approach makes it easier to manage complex problems by tackling them step
by step.

3. Global Data Access:

o Data in POP is often shared among functions. Variables are defined globally, and
functions operate on this global data.

o This can lead to issues like data corruption if multiple procedures are trying to
manipulate the same data at once.

4. Sequential Execution:

Page 3 of 27
o Instructions or functions are executed in a predefined sequence. The program
follows a clear flow of control where functions are called one after another based
on the program logic.

5. Modularity:

o The program is divided into modules or smaller sub-programs (procedures). Each


module handles a specific task, which enhances readability and maintainability.

o Code reuse is possible as functions can be reused across different parts of the
program.

6. No Data Encapsulation:

o Unlike Object-Oriented Programming (OOP), data and functions are not


encapsulated together in POP. This means that data is freely accessible by any
function, and there is no mechanism to restrict or control data access.

7. Efficiency in Smaller Programs:

o POP is efficient for small programs where the focus is on simple tasks. It is less
suitable for large, complex systems, as it lacks mechanisms like data
encapsulation and abstraction that are crucial in OOP.

Examples of programming language that follows POP are C, PASCAL, COBOL, etc.

Advantages of POP:

 Easy approach to solve the problem.

 Simple and easy to understand for smaller programs.

 Well-suited for tasks that can be easily broken down into steps.

 Functions are reusable across different parts of the program.

Disadvantages of POP:

 Not ideal for large or complex systems.

 Lack of data security due to no data encapsulation.

 Code can become difficult to manage with multiple global variables.

 Harder to model real-world problems compared to Object-Oriented Programming.

Page 4 of 27
Introduction to Object Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm centered around the concept


of "objects," which represent real-world entities. OOP organizes software design around data, or
objects, rather than functions and logic. Each object contains both data (attributes) and methods
(functions) that operate on that data, encapsulating the state and behavior of the object.

Key Features of Object-Oriented Programming:

1. Objects and Classes:

o Objects are instances of classes, which act as blueprints. A class defines the
attributes (data) and methods (functions) that the objects will have.

o Objects encapsulate the state (data) and behavior (methods) within a program.

o Example: In a class Car, objects could be car1, car2, etc., each representing a
specific car.

2. Encapsulation:

o Encapsulation is the bundling of data and methods that operate on that data
within a single unit (object).

o It restricts direct access to an object‘s data and only allows modifications through
its methods, promoting data security and preventing unauthorized access.

o Example: In a class BankAccount, only the account holder (via methods like
deposit or withdraw) can modify the balance.

3. Abstraction:

o Abstraction is the concept of hiding the complex implementation details and


showing only the necessary features of an object.

o It simplifies interaction with objects by exposing only what is necessary for the
user.

o Example: A Car class might expose methods like start and stop but hide complex
internal mechanisms like the engine's functioning.

4. Inheritance:

o Inheritance allows one class (child/subclass) to inherit the properties and


methods of another class (parent/superclass).

Page 5 of 27
o This promotes code reusability and hierarchical classification. Subclasses can add
new features or override existing ones.

o Example: A class Vehicle could have subclasses Car, Bike, and Truck, which
inherit common properties like no of tyres, speed and fuel but also have unique
features.

o Inheritance is called ―is a‖ relationship. The subclass "is-a" type of the superclass,
meaning it shares the common characteristics (attributes and methods) of the
parent but may also have additional, specialized features. For eg., Car is a Vehicle,
Bike is a Vehicle.

5. Polymorphism:

o Polymorphism allows methods or functions to behave differently based on the


object that calls them. Polymorphism, a Greek term, means the ability to take more
than one form or one name multiple forms. An operations may exhibit different
behaviors in different instances. The behavior depends upon the type of data used
in the operation.

o It can take two forms:

 Compile-time polymorphism (Method/Operator Overloading): A class


can have multiple methods with the same name but different parameter
lists.

 Run-time polymorphism (Method Overriding): A subclass can provide


a specific implementation of a method already defined in its parent class.

Function Overloading

When there are multiple functions with the same name but different parameters,
then the functions are said to be overloaded, hence this is known as Function

Page 6 of 27
Overloading. Functions can be overloaded by changing the number of arguments
or/and changing the type of arguments.

o Example: A method draw() might work differently for objects of classes Circle,
Rectangle, or Triangle, each having its own version of draw().

o NOTE: Runtime vs. compile time: Compile time is when programming code is
converted to machine code, while runtime is when a program is running. Runtime
generally occurs after compile time.

Operator Overloading

The process of making an operator to exhibit different behaviours in different instances is


known as operator overloading.

E.g., +(string1,string2); concatenates two string.

+(int,int); adds two int.

6. Dynamic Binding:
o Dynamic binding refers to the process where the method to be invoked is
determined at runtime, based on the object type.

o It enhances flexibility and allows for run-time decision-making based on the


object‘s actual class.

o Example: In a class hierarchy of shapes, a draw() method might be invoked


dynamically, based on whether the object is a Circle, Square, or Triangle.

o In C++ dynamic binding is implemented using virtual function.

Advantages of OOP:

 Reusability: Inheritance allows code to be reused, reducing duplication and improving


maintainability.

 Scalability: The modularity of OOP allows complex systems to be built from smaller,
independent objects.

 Maintainability: Encapsulation and abstraction simplify debugging and future


modifications.

 Security: Encapsulation restricts access to an object‘s data, reducing the chances of


accidental corruption.

Page 7 of 27
Disadvantages of OOP:

 Complexity: OOP can be more complex to implement, especially for smaller programs
where procedural programming might be simpler.

 Memory Overhead: The creation and management of objects require more system
resources compared to procedural programming.

 Slower Execution: The dynamic behavior (polymorphism, dynamic binding) might


result in slower performance compared to non-OOP paradigms.

In summary, Object-Oriented Programming provides a powerful way to model real-world


systems by organizing data and behavior into objects. OOP makes code more reusable,
maintainable, and modular, which is highly beneficial for developing large and complex software
systems.

Application of OOP:

1. Object oriented database systems.

2. Object oriented operation systems.

3. GUI (graphical user interface).

4. Windows based os design.

5. Simulation and modeling.

6. CAD, CAM.

7. Multimedia application.

8. Any kind of application or system software can be designed using OOP.

Examples of programming language that follows OOP are C++, JAVA, C#, Python, PHP, PERL,
RUBY, etc.

Difference between POP and OOP:

POP OOP

1. Emphasis is on algorithms (doing 1. Emphasis on data.


things).
2. Program is divided into functions. 2. Programs divided into objects.
3. Data move openly around the system. 3. Date and operations are tied in a data
structure. So data is hidden and cannot be
accessed.

Page 8 of 27
4. Function transforms data from one form 4. Objects communicate with each other
to another. through functions.

5. Follows top down approach. 5. Follows bottom up approach.


6. Cannot model real world problems very 6. Real world model can be modelled
well. easily with the help of objects.

7. Modifications and adding new functions 7. Very easy.


are tedious.

Overview and History of C++

 Developed by Bijarne Stroustrup at AT & T Bell Labs, USA in 1980‘s


 C++ combines the features of Simula and C along with Algol, Ada, Clu programming
languages
 Initially it was called ―C with Classes‖ and later it was renamed to C++.
 C++ is superset of C
 C++ is an OOP Language that can be used to develop platform independent software.

Structure of C++ programs

Include files
Class declarations
Member functions definitions
Main Function

In C++, programs often follow an organized structure that includes include files, a class
declaration, member function definitions, and the main function. Here's a breakdown of
each section with examples:

1. Include Files
Include files, also known as preprocessor directives, are used to include external libraries
or files needed by the program. These libraries may contain predefined classes and
functions for tasks like input/output, mathematics, etc. This is done using the #include
directive.
E.g., #include <iostream> // Allows input/output operations
Page 10 of 27
#include <string> // Allows string operations
2. Class Declaration
The class declaration defines a class, which is a user-defined data type in C++ that
encapsulates data (attributes) and functions (methods) that operate on the data. This
declaration typically includes:

 Access specifiers (e.g., public, private, protected)


 Attributes (Data Members): Variables defined inside the class.
 Member Functions: Functions that operate on the data members.

3. Member Function Definition

The member function definitions provide the actual implementation of the member
functions declared in the class. These are usually defined outside the class using the scope
resolution operator :: to indicate which class the function belongs to.

4. Main Function

The main function is the entry point of the C++ program, where the program begins
execution. Inside the main(), we can create objects of the class, call member functions, and
perform operations.

Note: Additional sections such as user defined function section, global declaration section
can also be included like in C language as C++ is superset of C.

An example of a C++ program with Class

//Program to accept and display person information

#include<iostream>

using namespace std;

class person

char name[10];

public:

void getdata(void);

void display(void);

};

Page 11 of 27
void person:: getdata(void)

cout<<―enter name‖;

cin>>name;

void person:: display(void)

cout<<name;

int main()

person p;

p.getdata();

p.display();

return 0;

Note: Namespaces allows the grouping of different entities such as classes, objects, functions and
a variety of C++ tokens, etc., under a single name. It is used to avoid same name conflicts.

To use the classes, objects, etc of a namespace we should use scope resolution operator ―::‖.

Eg., std: :cout<<―Hello World‖;

Keywords in C++

Keywords are predefined reserved identifiers that have special meanings. They cannot be used
as identifiers in your program. There are 63 keywords in C++. The following are some of the
keywords in C++.

Auto enum new this

Page 12 of 27
Break case for if
class structure int continue

Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item.

The general rules for naming variables are:

 Names can contain letters, digits and underscores

 Names must begin with a letter or an underscore (_)

 Names are case-sensitive (myVar and myvar are different variables)

 Names cannot contain whitespaces or special characters like !, #, %, etc.

 Reserved words (like C++ keywords, such as int) cannot be used as names

Constants

When you do not want others (or yourself) to change existing variable values, use the const
keyword (this will declare the variable as "constant", which means unchangeable and read-only).
It is fixed value and do not change during the program execution.

You should always declare the variable with constant keyword.

For e.g.,

const int minutesPerHour = 60;

const float PI = 3.14;

Comments in C++

 Single line Comments – // I will only extent to single line

 Double line comments – /* i will span to various ......................... different lines*/

Comments are used to increase the understandability enhancing readability of the code. Generally,
comments are written to help other coders, who are working on same application and want to
understand the code written by someone else.

Page 13 of 27
Variables

Variables are containers for storing data values. The value in the variable may be changed during
the program execution by the instructions.

In C++, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123

 double - stores floating point numbers, with decimals, such as 19.99 or -19.99

 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

 string - stores text, such as "Hello World". String values are surrounded by double quotes

 bool - stores values with two states: true or false

Note: object is also a kind of variable of type class.

Declaring (Creating) Variables

To create a variable, specify the type and mention the variable name. Initial value can be assigned
to the variable at the time of declaration.

Syntax

type variableName = value;

Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.

E.g.,

int myNum = 15;

Note: Rules for naming a variable is same as rules for naming an identifier.

Data types

In C++, data types define the type of data that a variable can hold. Or it refers the category of the
variable. It defines the type of operations that can be performed on the data and also determine the
size and type of information stored in a variable. C++ provides several categories of data types,
including built-in (or primitive) types, user-defined types, and derived types. Here‘s an overview
of the main data types in C++:

Summary of Data Types in C++:

Page 14 of 27
Category Data Type Description

int, char, bool, float, double,


Primitive Built-in basic types.
void

Derived Arrays, Pointers, References Derived from primitive types.

User- Allows creating new types tailored to specific


struct, union, enum, Classes
Defined needs.

1. Primitive (Built-in) Data Types

These are the most basic data types provided by C++.

a. Integer Types (int)

 Description: Used to store whole numbers (no decimal points).

 Size: Typically 4 bytes (on most systems).

 Range: Depends on the system, usually from -2^31 to 2^31 - 1.

b. Character Type (char)

 Description: Used to store a single character (a letter, digit, or symbol).

 Size: 1 byte.

 Range: From -128 to 127 or 0 to 255 (depending on whether it‘s signed or unsigned).

c. Floating-Point Types (float, double)

 Description: Used to store numbers with fractional parts (decimal points).

o float: 4 bytes, provides precision of up to 7 decimal digits.

o double: 8 bytes, provides precision of up to 15 decimal digits.

d. Boolean Type (bool)

 Description: Used to store true or false values.

 Size: 1 byte (though it can be optimized by the compiler).

 Values: true or false (internally, true is stored as 1 and false as 0).

Page 15 of 27
e. Void Type (void)

 Description: Indicates the absence of type. It is mainly used for:

o Functions that don‘t return a value (void functions).

o Generic pointers (void*).

2. Derived Data Types

These types are based on primitive types and are created using them.

a. Arrays

 Description: A collection of elements of the same type stored in contiguous memory


locations.

 Syntax: type arrayName[size];

E.g, int numbers[5] = {1, 2, 3, 4, 5};

b. Pointers

 Description: Variables that store the memory address of another variable.

 Syntax: type* pointerName;

E.g, int num = 10;

int* ptr = &num; // ptr holds the address of num

c. References

 Description: Alias for another variable. Once a reference is initialized, it cannot be


changed to refer to another variable.

 Syntax: type &referenceName = variableName;

E.g, int x = 10;

int &ref = x; // ref is a reference to x

3. User-Defined Data Types

C++ allows users to create their own data types to suit specific needs.

a. Structures (struct)

Page 16 of 27
 Description: A structure is a user-defined type that groups variables of different types
under a single name.

 Syntax: struct structureName { type member1; type member2; };

E.g, struct Person {

string name;

int age;

};

Person p1;

p1.name = "Mohan";

p1.age = 25;

b. Unions (union)

 Description: A union is similar to a structure, but all members share the same memory
location. It can only store one value at a time.

 Syntax: union unionName { type member1; type member2; };

E.g.,

union Data {

int intVal;

float floatVal;

};

Data data;

data.intVal = 10; // Now, data stores an integer

c. Enumerations (enum)

 Description: Used to define a set of named integral constants. Each constant in an enum
is assigned a unique value.

 Syntax: enum enumName { value1, value2, ... };

Page 17 of 27
E.g.,

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

Days today = Sunday;

d. Classes

 Description: A class is a user-defined data type that encapsulates data (attributes) and
functions (methods) that operate on the data. It is central to object-oriented programming
in C++. It is the blue print/template of object.

 Syntax: class className { access_specifier: members; };

E.g.,

class Car {

string brand;

int year;

public:

void display() {

cout << "Brand: " << brand << ", Year: " << year;

};

Type Conversion

Type conversion in C++ is the process of converting one data type to another. C++ provides two
types of type conversions:

1. Implicit Type Conversion (Automatic Type Conversion)

2. Explicit Type Conversion (Type Casting)

1. Implicit Type Conversion (Automatic Type Conversion)

Implicit type conversion occurs when the compiler automatically converts one data type to another
without the programmer's intervention. This usually happens when mixing different data types in
expressions or assignments.

Page 18 of 27
E.g.,

int a = 10;

double b = 5.5;

double result = a + b; // Implicit conversion of 'a' to double

Rules for Implicit Type Conversion:

 C++ promotes smaller types to larger types when they are mixed.

 Integer types can be promoted to float or double.

 Char is promoted to int when necessary.

2. Explicit Type Conversion (Type Casting)

In explicit type conversion, the programmer manually converts one data type to another using type
casting. C++ provides several ways to do type casting:

Syntax: type(expression);

E.g.,

int a = 10;

double b = double(a); // C++ style casting of 'a' to double

Operators

In C++, operators are symbols that perform operations on variables and values. These operators
can be categorized into different types based on their functionality. Here's an overview of the
various types of operators in C++:

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations on operands.

Operator Description Example

+ Addition a+b

- Subtraction a–b

* Multiplication a*b

Page 19 of 27
Operator Description Example

/ Division a/b

% Modulus (Remainder) a % b

E.g., int a = 10, b = 3;

cout << a + b; // Output: 13

cout << a % b; // Output: 1

2. Relational (Comparison) Operators

Relational operators are used to compare two values. The result is a boolean value (true or false).

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

E.g,

int a = 10, b = 20;

cout << (a == b); // Output: 0 (false)

cout << (a < b); // Output: 1 (true)

3. Logical Operators

Logical operators are used to combine multiple relational conditions. The result is also a boolean
value.

Page 20 of 27
Operator Description Example

&& Logical AND a && b

|| Logical OR a || b

! Logical NOT !a

E.g.,

bool a = true, b = false;

cout << (a && b); // Output: 0 (false)

cout << (a || b); // Output: 1 (true)

cout << (!b); // Output: 1 (true)

4. Assignment Operators

Assignment operators are used to assign values to variables.

Operator Description Example

= Assign a=b

5. Increment and Decrement Operators

These operators are used to increase or decrease the value of a variable by 1.

Operator Description Example

++ Increment by 1 ++a

-- Decrement by 1 --a

There are two types of increment and decrement operators:

 Prefix: ++a, --a (Increments/Decrements the value before using it)

 Postfix: a++, a-- (Uses the value first, then increments/decrements)

int a = 5;

cout << ++a; // Output: 6 (Prefix: Incremented before use)


Page 21 of 27
cout << a++; // Output: 6 (Postfix: Used before increment)

6. Bitwise Operators

Bitwise operators perform operations at the bit level. These operators work on binary
representations of integers.

Operator Description Example

& Bitwise AND a & b

| | Bitwise OR

^ Bitwise XOR a ^ b

~ Bitwise NOT ~a

<< Left shift a << 1

>> Right shift a >> 1

E.g,:

int a = 5, b = 3; // a = 0101, b = 0011 in binary

cout << (a & b); // Output: 1 (0001 in binary)

cout << (a | b); // Output: 7 (0111 in binary)

7. Conditional (Ternary) Operator

The ternary operator is a shorthand for if-else conditions. It takes three operands: a condition, a
result if true, and a result if false.

Operator Description Example

?: Condition ? Value_if_true : Value_if_false (a > b) ? a : b

E.g.,

int a = 10, b = 20;

int max = (a > b) ? a : b; // Output: max = 20

Page 22 of 27
9. Comma Operator

The comma operator , is used to separate multiple expressions, and it evaluates from left to right.

E.g.,

int a, b, c;

a = (b = 2, c = 3, b + c); // a = 5

10. Pointer Operators

These operators are used to work with memory addresses.

Operator Description Example

& Address of &a

* Dereference (value at address) *ptr

E.g.,

int a = 10;

int *ptr = &a; // ptr stores the address of a

cout << *ptr; // Output: 10 (value at address ptr)

11. Scope Resolution Operator

The scope resolution operator :: is used to define a function outside the class or to access a global
variable when there's a local variable with the same name.

E.g.,

int a = 10;

class Example {

public:

void display() {

cout << ::a; // Accesses the global variable a

};

Page 23 of 27
Note: scope resolution operator is used in defining member functions and using objects/identifiers
of namespaces.

12. Sizeof Operator

The sizeof operator returns the size of a variable or data type in bytes.

E.g.,

int a;

cout << sizeof(a); // Output: 4 (size of int on most systems)

13. New and Delete Operators

The new operator dynamically allocates memory, and the delete operator frees the memory.

Example:

int* ptr = new int(5); // Dynamically allocates memory for an integer

delete ptr; // Frees the allocated memory

Precedence of operators

In C++, operator precedence determines the order in which operators are evaluated in expressions.
This affects how expressions are parsed and computed. Operators with higher precedence are
evaluated before operators with lower precedence. If two operators have the same precedence,
associativity rules determine their evaluation order.

Operator Precedence and Associativity

1. Operators with the Highest Precedence

o Parentheses (): Used to override the default precedence and specify the order of
evaluation.

o Unary Operators: ++ (prefix increment), -- (prefix decrement), + (unary plus), -


(unary minus), ! (logical NOT), ~ (bitwise NOT), * (dereference), & (address-of),
sizeof, typeid, dynamic_cast, static_cast, const_cast, reinterpret_cast

2. Binary Arithmetic Operators

o Multiplicative: * (multiplication), / (division), % (modulus)

o Additive: + (addition), - (subtraction)

Page 24 of 27
3. Relational Operators

o == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or
equal to), <= (less than or equal to)

4. Logical Operators

o Logical AND: &&

o Logical OR: ||

5. Assignment Operators

o = (assignment), +=, -=, *=, /=, %= (compound assignments)

6. Bitwise Operators

o Shift: << (left shift), >> (right shift)

o Bitwise AND: &

o Bitwise XOR: ^

o Bitwise OR: |

7. Conditional Operator

o ? : (ternary conditional)

8. Comma Operator

o , (evaluates multiple expressions)

Associativity

Associativity defines the order of operations for operators with the same precedence level:

 Left-to-Right: Most operators, including arithmetic, relational, and bitwise operators, are
evaluated from left to right.

 Right-to-Left: Assignment operators, conditional operators, and unary operators are


evaluated from right to left.

E.g.,

int a = 5;

int b = 10;

Page 25 of 27
int c = 15;

int result = a + b * c; // Multiplication (*) has higher precedence than addition (+)

// result = 5 + (10 * 15) = 5 + 150 = 155

Expressions

In C++, expressions are combinations of variables, constants, operators, and functions that
evaluate to a value. They are fundamental to writing programs, as they perform calculations, make
decisions, and control the flow of the program. Here‘s a detailed explanation of different types of
expressions in C++:

1. Arithmetic Expressions

Arithmetic expressions use arithmetic operators to perform mathematical operations. They operate
on numeric values and variables.

E.g., int sum = a + b; // Arithmetic expression: evaluates to 15

2. Relational (Comparison) Expressions

Relational expressions compare two values and return a boolean result (true or false).

E.g.,

int a = 10;

int b = 20;

bool result1 = (a == b); // Comparison expression: evaluates to false

3. Logical Expressions

Logical expressions combine boolean values or relational expressions using logical operators.

E.g.,

bool a = true;

bool b = false;

bool result1 = a && b; // Logical expression: evaluates to false

4. Assignment Expressions

Assignment expressions assign a value to a variable and return the assigned value.

E.g.,
Page 26 of 27
int c,a = 10,b =5;

c = a+b; // Assignment expression: c is now 15

Storage Classes: It provides the information about variable visibility or scope, lifetime and storage
location. There are 4 types of storage classes they are:

1. Auto storage classes.


2. Register storage classes.
3. Static storage classes.
4. Extern storage classes.
NOTE: The default storage class is auto storage class.
Scope or visibility refers to the area of existence in a program and lifetime refers to the time period
in which the variable has valid memory.
1. Auto storage class: It is a default storage class.
Syntax: auto data type variable name;
Example: auto int x;
Storage location: computer memory.
Scope or visibility: local visibility or local scope (only within the function block)
Life time: only within the function block.
Default value: garbage or junk value.
2. Register storage class: Store the data in CPU registers.
Syntax: register data type variable name;
Storage location: CPU registers.
Scope: local (only within the function block)
Life time: only within the function block.
Default value: garbage or junk value.
3. Extern Storage class: An extern variable is either a global variable or variable defined in
another source file.
Syntax: Extern data type variable name;
Example: extern int x;
Storage location: memory.
Scope: global (main and user defined function section).
Life time: entire program.
Default value: 0
4. Static storage class: Static storage class retains the value of the variable between multiple
function call.
Syntax: static data type variable name;
Example: static int x;
Storage location: memory.
Scope: local (within the function).
Life time: Entire program.
Default value: 0.

Page 27 of 27
VISION OF THE INSTITUTE

Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.

MISSION OF THE INSTITUTE

To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.

Lecture Notes on Problem Solving using C++ (LTP::3:0:0)


Course Code: DSC12T 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

BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.

Prepared by: Dr. Chandrajit M

Department: Computer Science

Page 1 of 25
Unit-2

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


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

Control Statements
Control Statements are used to control the flow of execution of the program execution. They allow
the program to make decisions, execute specific code blocks, and repeat code sections. Selection
statements( Decision Making Statements), Looping Statements, Jumping statements are types of
control statements.

Selection Statements:
In order to execute or skip a set of instructions based on certain conditions we require the help of
decision making and branching or conditional or selection statements.

C++ language supports the following selection statements:

1. if statement
2. switch statement

The different types of if statements are:


a. Simple if statement.
b. if-else statement.
c. Nested –if statement.
d. Else-if ladder statement.

a. Simple-if statement: It contains only the if block which is used to execute set of statements
based on certain condition.
Statements will be executed only when the condition in the expression is true.
Syntax: if(condition)
{
Set of statements
}
The condition expressed may be logical or relational or expression.

E.g.,
if (age >= 18) {
cout << "Adult";
} else {
cout << "Not an adult";
}

Page 2 of 25
Flow Chart:

if
conditi

True

Statement inside the if block False

Next statement

Program To Check Whether The Number Is Even Or Odd Using Simple If Statement:
//Program to check the number is even or odd
#include<iostream.h>
void main()
{
int n;
cout<<‖enter the value for n‖;
cin>>n;
if(n%2==0)
{
cout<<―n is even‖;
}
if(n%2!=0)
{
cout<<―n is odd‖;
}
}
b. If-else statement: The if-else statement is a conditional statement which executes the set
of statements in the if block if the condition is true otherwise set of statement within the
else block will be executed. The if-else statement helps in two way decision making.

Syntax: if(condition)
{
Set of statements

}
else
{

Page 3 of 25
Set of statements.
}

Program To Check Whether The Number Is Even Or Odd:


//Program to check the number is even or odd
#include<iostream.h>
void main()
{
int n;
cout<<‖enter the value for n‖;
cin>>n;
if(n%2==0)
{
cout<<―n is even‖;
}
else
{
cout<<―n is odd‖;
}
}

c. Nested-if statement: If an if-else statement is placed inside another if-else statement, then
it is called nested-if statement.
Syntax: if(condition)
{
if(condition)
{
Set of statements

}
else
{
Set of statements
}
}
else
{
Set of statements
}

E.g., Program To Check Whether The Number Is Positive Or Negative Or Zero:


//Program to check the number is positive, negative or zero
#include<iostream.h>
#include<conio.h>

Page 4 of 25
void main()
{
int n;
clrscr();
cout>>‖Enter the value for n‖;
cin>>n;
if(n>=0)
{
if(n==0)
{
cout<<―n is zero‖;
}
else
{
cout<<―n is positive‖;
}
}
else
{
cout<<―n is negative‖;
}
getch();
}

d. Else-if ladder: It is used to select one block out of multiple blocks. It is helpful in multi-
level decision making.
Syntax: if(condition)
{
Set of statements
}
else if(condition)
{
Set of statements
}
else if(condition)
{
Set of statements
}
else
{
Set of statements
}

Page 5 of 25
Program To Display The Total Marks , Grade And Percentage Of Subjects:
#include<iostream.h>
#include<conio.h>
void main()
{
int m1,m2,m3,flag=0,total;
float percentage;
clrscr();
cout<<―enter the marks for m1,m2,m3‖;
cin>>m1>>m2>>m3;
if(m1<35||m2<35||m3<35)
{
flag=1;
}
total=m1+m2+m3;
percentage=float(total)/3;
if(flag==1)
{
cout<<―result=fail‖;
}
else if (percentage >70)
{
cout<<―distinction‖;
}
else if(percentage>60)
{
cout<<―first class‖;
}
else if(percentage>50)
{
cout<<―second class‖;
}
else
{
cout<<―pass class‖;
}
getch();
}

2. SWITCH STATEMENT: It is used for multilevel decision making. It executes one


block out of many block. The expression in the switch can be either integer or character
only. It is similar to else if ladder.

Page 6 of 25
Syntax: switch(expression)
{
case label: statements;
break;
case label: statements;
break;
.
.
.
default :
break;
}

Program To Check The Input Is A Vowel Or A Consonant:

#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
cout<<―enter the character‖;
cin>>ch;
switch(ch)
{
case ‗a‘:
case ‗e‘:
case ‗i‘:
case ‗o‘:
case ‗u‘: cout<<―vowel‖;
break;
default: cout<<―consonant‖;
break;
}
getch();
}

Nested switch statement: If a switch statement is placed inside another switch statement, then
it is called as nested switch statement.
Syntax: switch(expression)
{
case label: switch(expression)
{
case label: statements
break;

Page 7 of 25
.
.
.
default: statements
break;
}
case label: statements;
break;
default: statements;
}

Program Using Nested Switch Statement:


Departments: Designations:
1. Sales. 1. Executive.
2. Marketing. 2. Manager.

#include<iostream.h>
#include<conio.h>
void main()
{
int dept,desi;
clrscr();
cout<<―enter the value for department 1.sales 2.marketing‖;
cin>>dept;
cout<<―enter the value for designation 1.executive 2.manager‖;
cin>>desi;
switch(dept)
{
case 1: switch(desi)
{
case 1: cout<<―executive in sales‖;
break;
case 2: cout<<―manager in sales‖;
break;
}
break;
case 2: switch(desi)
{
case 1: cout<<―executive in marketing‖;
break;
case 2: cout<<―manager in marketing‖;
break;
}
break;
} getch();
}

Page 8 of 25
Looping/Iteration/Repetition Statements:
Looping statements are also called as iterative statements. It is used to execute a block of
statements repeatedly as long as some conditions are satisfied.
There are three steps in looping statement:
1. Initialization: Used as starting point of iteration.
2. Condition: Used to terminate the iteration.
3. Step: Used to either increment or decrement the initialized variable for repetition.
The variable which is used in all the above steps are called loop control variable.
There are three types of looping statements:
a. While loop.
b. Do-while loop.
c. For loop.
 While loop: While loop is an entry controlled loop which executes the block of statements
repeatedly as long as the condition in the expression is true. It is also called as pre-test loop.
Syntax: initialization
while(condition)
{
Block of statements
Increment /decrement the initialized variable
}

FLOW CHART FOR WHILE LOOP:

STAR

INPUT

INITIALIZATION

CONDI
False
TION

True NEXT STATEMENT

BLOCK OF STATEMENTS
STOP

INCREMENT/DECREMEN

Page 9 of 25
Program to Generate First N Natural Numbers:

//Program to generate first n natural numbers


#include<iostream>
#include<conio.h>
void main()
{
int i ,n;
clrscr();
cout<<―enter the value for n‖;
cin>>n;
i=0;
while(i<=n)
{
cout<< i;
i++;
}
getch();
}

Program to Generate Multiplication Tables Of A Number:

//Multiplication table
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i,ans;
clrscr();
cout<<―enter the value for n‖;
cin>>n;
i=1;
while(i<=10)
{
ans=n*i;
cout<<n<<‖x‖<<i<<‖=‖<<ans<<endl;
i++;
}
getch();
}

 Do-while loop: The do-while is called as exit controlled statement. The statement block
will execute as long as the condition holds good or true. Entry to the do-while statement
before the testing of condition makes the block of statements to execute at least once. It is
called the post-test loop.

Page 10 of 25
Syntax: Initialization of control variable
do
{
//statement block
[increment/decrement of control variable]
} while(condition);

Flow Chart for Do-While Loop:

STAR

INPUT

INITIALIZATION

STATEMENT BLOCK

True CON false


DI-

NEXT STATEMENT

STOP

Page 11 of 25
Program To Simulate The Operations of Simple calculator:

#include<iostream.h>
#include<conio.h>
void main()
{
float n1,n2,res;
int choice;
char ch=‘y‘;
clrscr();
do
{
cout<<―1-Add 2-Sub 3-Mul 4-div‖<<endl;
fflush(stdin);
cin>>choice;
cout<<―enter 2 numbers‖;
cin>>n1>>n2;
switch(choice)
{
case 1: res=n1+n2;
cout<<―sum=‖<<res;
break;
case 2: res=n1-n2;
cout<<―diff=‖<<res;
break;
case 3: res=n1*n2;
cout<<―product=‖<<res;
break;
case 4: res=n1/n2;
cout<<―division=‖<<res;
break;
default: cout<<―invalid choice‖;
}
cout<<―do you wish to continue Y/N‖;
cin>>ch;
} while(ch==‘Y‘)
getch();
}

Page 12 of 25
Difference Between While And Do-While Loop:

While loop Do-while loop


1. It is a pre-test loop. 1. It is a post-test loop.
2. The while loop do not run if the 2. The do-while loop runs at least once,
condition is false. It comes out of the even though the condition is false.
loop.
3. While is an entry controlled loop. 3. Do-while is an exit controlled loop.
4. Syntax: Initialization 4. Syntax: Initialization of control
while(expression) variable
{ do
Block of statements {
Increment/decrement //statement block
Initialized variable Increment
} /decrement
} while(condition);

 for loop: The for loop works in the same manner as the while loop except the initialization
condition and increment/decrement are all part of the syntax. That is, it is an iterative
statement which takes care of the initialization, condition and increment/decrement.

Working of For Loop:


1. Initialization.
2. Condition. Goto step 4 if condition fail.
3. Entry to the body of the loop.
4. Increment/decrement. Goto step 2.
5. Exit from body of the loop.
Syntax: for(initialization ; condition ; increment/decrement)
{
set of statements
}

Program To Generate Multiplication Tables Using For Loop:

#include<iostream.h>
#include<conio.h>
void main()
{
int n,i,ans;
clrscr();
cout<<―enter the value for n‖;
cin>>n;

Page 13 of 25
for(i=1;i<=10;i++)
{
ans=n*i;
cout<<n<<‖x‖<<i<<‖=‖<<ans<<endl;
}
getch();
}

 NESTING OF LOOPS: Cascading of loops is called nesting of loops. That is one loop is
placed inside the body of another loop.
Example: for (initialization ; condition ; increment/decrement)
{
while(condition)
{
Set of statements
}
}
Working of nested loops: Always the inner loop will finish all the iterations and then the
outer loop will go for next iteration.

Program to Generate Multiplication Tables For M To N Numbers:

#include<iostream.h>
#include<conio.h>
void main()
{
int n,m,i,p,j;
clrscr();
cout<<―enter the values for m and n‖;
cin>>m>>n;
for(i=m;i<=n;i++)
{
for(j=1;j<=10;j++)
{
p=j*i;
cout<<j<<‖x‖<<i<<‖=‖<<p<<endl;
}
}
getch();
}

Program to Display The Following Pattern:


*****
*****
*****
for(i=1;i<=3;i++)

Page 14 of 25
{
for(j=1;j<=5;j++)
{
cout<<―*‖;
}
cout<<endl;
}

Logic to Display The Following Pattern:


*
**
***
****
*****
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
cout<<“*”;
}
cout<<endl;
}

Jumps in Loops/Sequence Control Statement:

1. Break: The break statement is used to come out of the loop that is stop the iteration. It is
also used in switch statement to exit from the block.

Syntax: break;

Example: for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
cout<<i;
}

Output: 1
2
3
4
2. Continue: Continue statement is used to skip the current iteration and continue with the
next iteration. All the iterations will be executed in the continue statement if we use

Page 15 of 25
continue statement, where as if we use break statement the loop will not execute all the
iterations.
Syntax: continue;
Example: for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
cout<<i ;
}
Output: 1
2
3
4
6
7
8
9
10
3. Exit: Exit statement is used to terminate the current program. All the storage area will be
cleared.
Syntax: exit(0);
Example: void main()
{
statements
exit(0);
}
exit(0) Stops executing the program and clears all the associated memory of variables.
exit(0) exit with no errors.
exit(1) exit with some errors.

Page 16 of 25
Modular Programming

Functions:
A function is a set of statements that perform a particular task. Functions helps us to achieve
moo Every C++-program contains at least one function, which is the main() function.
Types of functions:
1. Built-in functions.
2. User-defined functions.

1. Built-in functions: These are the functions which comes along with the C++ compiler
which can be used by specifying the associated header file in the program.

Example:
strcst(),strstr(),strcmp(),gets(),puts() are present in string.h header files.
Sqrt(), sin(), pow(), etc., are present in math.h header files.

2. User-defined functions: These are the functions that are created by the developers for
solving a particular task.
Example: sorting(), searching(), factorial() etc
Functions are also called as methods, sub-programs, sub-routine, procedure, sub-
procedure.
Advantages of functions:
 Functions avoid repetition of codes that is; functions written once can be used again and
again.
 It increases problem readability.
 Through structured programming approach or modular programming approach or top
down design we can break down a complex problem into smaller functions.
 Modifying of a program becomes easier by using functions.
 Saves lines of codes.

Steps in Function creation:


Function creation in C++ involves three steps:

STEP1: Write the function prototype in the global declaration section, that is giving
information to compiler about the function name, arguments and return value.
STEP2: Define the function that is writing the instructions of the functions to do a
particular task. Declare the datatype of return value and declare the function arguments.
STEP3: Use the function by calling its name and passing argument if any.

Note: Arguments/parameters are values which are supplied to the function. Return value
is the value returned by the function.

For example: Program to compute factorial of a number using functions.


#include<iostream.h>
int fact(int); //function prototype
void main()
{
Page 17 of 25
int num, res;
cout<<‖Enter a number‖;
cin>>num;
res=fact(num); //function call
cout<<‖Factorial of‖<<num<<‖=‖<<res;
}
// function to compute factorial
int fact(int n)
{
int i, f=1;
for(i=1;i<=n;i++)
f=f*1;

return(f);
}

Working:
 Firstly compiler will call main function.
 When control comes inside the main function, statements will be executed in sequence.
 Here in the above example we have called a function fact by passing a argument num.
 Now control goes to the fact function and executes the statements and returns the computed
factorial value ie., f.
 Function will return value f to the calling function(main). It will start executing from the
same place it was called.
 Returned value will be assigned to variable ―res‖ and displayed as output in the next steps.
 Main function ends.
 Program terminates.

Syntax for declaring prototype of function:


Function prototype is used to inform the complier about the user defined function. It is
written in the global declaration section.
Syntax:
returntype function name(argument list);
Example:
int largest(int, int);

Syntax for defining a function:


return type function name(datatype arg1 datatype arg2)
{
local declaration
statements
return value[variable]
}

Page 18 of 25
Example:
int largest(intx, inty)
{
if(x>y)
return x;
else
return y;
}

As per the syntax we can return one value, but to return more than one variable we can use
arrays/pointers.
Syntax for calling the function:
function name(arguments);
Example: largest(x,y);

Communication between functions:


Compunction happens by invoking the function and passing arguments and the function
executes and may return value.
There are two types of parameters or arguments:
1. Actual parameter: Arguments found in the function call is called as actual parameter.
2. Formal parameter: Arguments found in the function definition is called as formal
parameter.

Types of functions: Functions are classified into different types based on arguments and
return type.

1. Functions with arguments and return type:


It is type of function that contains both arguments and return type.
Syntax: return datatype function name(arguments)
{
body of the function
return value;
}

Example: Program to Compute Largest Of Two Numbers Using Functions:

#include<iostream.h>
#include<conio.h>
int largest(int, int)
void main()
{
int n1,n2,res;
clrscr();
cout<<―enter two numbers‖;
cin>>n1<<n2;
res=largest(n1,n2);

Page 19 of 25
cout<<―largest=‖<<res;
}
int largest(int n1, int n2)
{
if(n1>n2)
{
return n1;
}
else
{
return n2;
}
}
2. Function with argument and without return value:
It is a type of function that contains argument but does not return value.
Syntax: void function name(argument)
{
body of the function
}
Example: Program To Compute Largest Of Two Functions:
#include<iostream.h>
#include<conio.h>
void largest(int, int);
void main();
{
int n1,n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;
largest(n1, n2);
}
void largest(int n1,int n2)
{
if(n1>n2)
cout<<―largest=‖<<n1;
else
cout<<―largest=‖<<n2;
}

3. Functions Without Arguments And With Return Value:


It is a type of function that returns value but does not have arguments.
Syntax: Data type function name()
{
body of the function
}

Page 20 of 25
Example: Program To Compute Largest Of Two Numbers:
#include<iostream.h>
#include<conio.h>
int largest();
void main()
{
int res;
res=largest();
cout<<―largest=‖<<res;
}
int largest()
{
int n1, n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;
if(n1>n2)
{
return n1;
}
else
{
return n2;
}
}

4. Functions Without Arguments And Return Value:


It is a type of function that does not contain both arguments and return value.
Syntax: void function name()
{
body of the function.
}

Example: Program To Compute Largest Of Two Numbers:

#include<iostream.h>
#include<conio.h>
void largest();
void main()
{
largest();
}
void largest()
{
int n1,n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;

Page 21 of 25
if(n1>n2)
{
cout<<―largest=‖<<n1;

}
else
{
cout<<―largest=‖<<n2;

}
}

Recursion:
When a function calls itself from its body it is called as recursion.
Syntax: datatype function_name(argument)
{
function_name(argument);
}

Example: Program To Compute Factorial Of A Number Using Recursion:

#include<iostream.h>
#include<conio.h>
void main()
{
intn,f=0;
clrscr();
cout<<―enter the number‖;
cin>>n;
f=fact(n);
cout<<―factorial=‖<<f;
getch();
}
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*fact(n-1));
}
}

Page 22 of 25
Advantages of recursion:
 Reduces complexity of the problem.
 Through recursion one can solve problems in an easy way.

Disadvantages of recursion:
 Recursive solution is always logical and it is very difficult to trace.
 Recursion consumes a lot of stack spaces(memory).
 Recursion uses more processor time.

Functions with Default Arguments


 Definition: Default arguments in functions allow parameters to be given default values
when the function is called without specifying those parameters.
 Usage: If the arguments are omitted during the function call, the default values are used.
 Syntax: Define default values in the function prototype or function definition.

void greet(string name = "MIT FGC") {


cout << "Hello, " << name << "!" << endl;
}
// Calling greet() will output "Hello, MIT FGC!"
// Calling greet("Mohan") will output "Hello, Mohan!"

Note: Once a parameter is assigned a default value, all parameters to its right must also
have default values.

Inline Functions
 Definition: An inline function is a function where the compiler attempts to expand
the function code at the point of each call, rather than invoking the function in the
standard way. i.e. the function code itself is made available at the function call and
no transfer to the function takes place like the way in standard functions.
 Purpose: Useful for small, frequently used functions as it can help reduce function
call overhead and improve performance.
 Syntax: Declared using the inline keyword before the function.

inline int add(int a, int b)

return a + b;
}

Note: Inline is a request, not a command; the compiler may ignore it if the function is too
complex or recursive.

Page 23 of 25
Function Overloading
 Definition: Function overloading allows the same function name to be used for
different functions that differ in their parameter lists (number or type of
parameters). It is a form of polymorphism.
 Purpose: Enables functions with the same name but different types or numbers of
arguments, improving readability and code reusability.
Example:

int add(int a, int b)


{
return a + b;
}

double add(double a, double b)


{
return a + b;
}

Note: The return type alone is not enough to distinguish overloaded functions.

Parameter Passing Mechanisms:


There are two ways to pass value or data (parameter/arguments) to function:
1. Call by value: Actual parameter values are copied to formal parameter. In call by
value, modification of formal parameter in the function will not affect the original
value ie., actual values.

Example: Program For Swapping Two Numbers Using Call By Value:


#include<iostream.h>
#include<conio.h>
void main()
{
int x=10, y=20;
cout<<―Before Swap: x=‖<<x<<‖y=‖<<y;
swap(x,y);
}
void swap(int m, int n)
{
int temp;
temp=m;
m=n;
n=temp;
cout<<―After Swap: x=‖<<x<<‖y=‖<<y;
}

Page 24 of 25
2. Call by reference: A reference (alias) to the actual argument is passed, so changes
made to the parameter affect the original argument.

Program For Swapping Two Numbers Using Call By Reference:


#include <iostream>
int main()
{
int a=9; // variable initialization
int b=10; // variable initialization
swap(a, b); // function calling
std::cout << "value of a is :" <<a<< std::endl;
std::cout << "value of b is :" <<b<< std::endl;
return 0;
}
void swap(int &p, int &q) // function definition
{
int temp; // variable declaration
temp=p;
p=q;
q=temp;
}

Math Library Functions


 Definition: C++ provides a set of mathematical functions in the <cmath> library for
performing common mathematical operations. Also, <math.h> library can also be used but
this is a C library.
 Common Functions:
o sqrt(x): Computes the square root of x.
o pow(x, y): Raises x to the power of y.
o abs(x) or fabs(x): Computes the absolute value of x.
o ceil(x): Rounds x up to the nearest integer.
o floor(x): Rounds x down to the nearest integer.
o sin(x), cos(x), tan(x): Computes the trigonometric values for x.
Example:

#include <cmath>
double result = sqrt(25); // result is 5.0

Page 25 of 25
VISION OF THE INSTITUTE

Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.

MISSION OF THE INSTITUTE

To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.

Lecture Notes on Problem Solving using C++ (LTP::3:0:0)


Course Code: DSC12T 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

BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.

Prepared by: Dr. Chandrajit M

Department: Computer Science

Page 1 of 23
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 with Manipulators.
User Defined Data Type: Class Definition, Instance Variables, Member Methods,
Accessing Members, Access specifiers, this pointer, Friend Function, Constructors, Types
of Constructors, Destructor.

Derived Data Types

Arrays

 Definition: An array is a collection of elements of the same type, stored in contiguous


memory locations.
 Syntax: data_type array_name[array_size];
 Example:

int n[5] = {1, 2, 3, 4, 5};

Memory representation:
0 1 2 3 4

n[0] n[1] n[2] n[3] n[4]

Initializing an array: int age[3]={20,23,26};

 Note: Array indices start from 0, so numbers[0] refers to the first element.

Array Types

 One-Dimensional Arrays: A linear collection of elements (e.g., int arr[10];).


 Multi-Dimensional Arrays: Arrays with more than one index, such as two-dimensional
arrays (e.g., int matrix[3][3]; for a 3x3 matrix).

Initializing 2-d array:

int a[3][3]={ {1,2,3}, {2,2,3}, {3,2,3} };

Page 2 of 23
Memory representation:
0 1 2
0 0,0 0,1 0,2

1,0 1,1 1,2


1
2,0 2,1 2,2
2

Examples:

Program to Display Sum And Average Of An Array:

#include<iostream.h>
#include<conio.h>
void main()
{
int a[100],n,i,sum=0;
clrscr();
cout<<enter the number of elements you want to insert:‖;
cin>>n;
for(i=0;i<n;i++)
{
cout<<―enter the element %d:‖<<i+1<<endl;
cin>>a[i])
sum=sum+a[i];
}
cout<<‖the sum of an array is:‖<<sum;
cout<<‖ the average of an array is:‖<<float (sum)\n;
getch();
}

Program To Compute The Sum Of Upper and Lower Diagonal Elements Of A Matrix:

#include<iostream.h>
#include<conio.h>
void main()
{
int a[100][100],n,i,j,sumlower,sumupper;
clrscr();
cout<<―enter the size of an array‖;
cin>>n;
cout<<―enter %d elements of the matrix‖;
for(i=0;i<n;i++)

Page 3 of 23
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i<j)
{
sumupper=sumupper+a[i][j];
}
if(i>j)
{
sumlower=sumlower+a[i][j];
}
}
cout<<―sum of lower diagonal elements=‖<<sumlower;
cout<<‖sum of upper diagonal elements=‖<<sumupper;
getch();
}

Strings

 Definition: Strings are sequences of characters. In C++, strings can be handled as character
arrays or as objects of the std::string class.
 Character Array Syntax: char str[] = "Hello";
 String Class Syntax: std::string str = "Hello";

String Manipulation Functions

 String Class Methods (from <string>):


o .length() or .size(): Returns the length of the string.
o .substr(pos, len): Returns a substring from the specified position.
o .find(sub): Finds the position of sub in the string.
o .at(): Returns an indexed character from a string.
o .append(): Appends a string (or a part of a string) to another string.
o .compare(): Compares two strings.

The compare() function compares two given strings and returns the following
results based on the matching cases:

Page 4 of 23
 If both the strings are the same, the function returns 0.
 If the character value of the first string is smaller than the second string,
the function returns < 0.
 If the second string is greater than the first string, the function returns
greater than 0 or >0.

Examples:

#include <iostream>
#include <string>
using namespace std;

int main () {
string txt = "MIT FGC";
cout <<"Char at(1) ="<< txt.at(1) <<endl;
cout<< "Lenght of string="<<txt.length()<<endl;
cout<<"Sub String ="<<txt.substr(4,6)<<endl;
cout<<"Find position="<<txt.find("F")<<endl;
string s1="MIT", s2="MIT";
cout<<"Compare="<<s1.compare(s2);
return 0;
}

Array of strings

// C++ program to demonstrate array of strings using string class


#include <iostream>
#include <string>

using namespace std;

// Driver code
int main()
{
// Initialize String Array
string colour[4] = { "Blue", "Red", "Orange", "Yellow" };

// Print Strings
for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";

return 0;
}

Page 5 of 23
Pointers

 Definition: A pointer is a variable that stores the memory address of another variable.
 Syntax: data_type* pointer_name;
 Example:

int num = 10;


int* ptr = &num;

 Note: * is used to declare a pointer, while & is used to get the address of a variable.

Pointer Arithmetic

Definition: Allows performing arithmetic operations on pointers (like +, -). There are four
arithmetic operators that can be used on pointers: ++, --, +, and -. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer

 Example:

int arr[5] = {10, 20, 30, 40, 50};


int* ptr = arr;
ptr++; // Points to the second element

 Note: When adding or subtracting from a pointer, it moves by the size of the data type.

Increment (++):
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points
to the address 1000 (Assuming 32-bit integers).
Example:
ptr++;

After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without
impacting the actual value at the memory location.
The following program increments the variable pointer to access each succeeding element
of the array:

#include <iostream.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr;
Page 6 of 23
/* let us have array address in pointer */
ptr = var;

for ( i = 0; i < MAX; i++) {

cout<<"Address of var[]‖<< i<<‖=‖<< ptr;


cout<<‖Value of var[]‖<<‖ = ―<<i<< *ptr;

/* move to the next location */


ptr++;
}

return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200

Decrement (--): Similar to increment. In this case it will decrease the value by number of
bytes.

Addition (+): We can add a value to the pointer variable. The formula of adding value to
pointer is given below: Adding any number to a pointer will give an address.
new_address= current_address + (number * size_of(data type))
For 64-bit int variable, it will add 4 * number.

#include<iostream.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
cout<<"Address of p variable is‖<<p;
p=p+3; //adding 3 to pointer variable
cout<<"After adding 3: Address of p variable is‖<<p;
return 0;
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312

Page 7 of 23
Subtraction (-): Similar to addition.

Illegal arithmetic with pointers:


There are various operations which cannot be performed on pointers. Since, pointer stores
address hence we must ignore the operations which may lead to an illegal address, for
example, addition, and multiplication. A list of such operations is given below.
 Address + Address = illegal
 Address * Address = illegal
 Address % Address = illegal
 Address / Address = illegal
 Address & Address = illegal
 Address ^ Address = illegal
 Address | Address = illegal
 ~Address = illegal

Managing Console I/O Operations

C++ Stream

 Definition: Streams in C++ are used to perform input and output operations. cin is the
standard input stream, and cout is the standard output stream.
 Syntax:

cout << "Enter a number: ";


cin >> num;

C++ Stream Classes: Stream classes in C++ are used to input and output operations on files and
io devices. These classes have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.

 Classes:
o istream: For input operations.
o ostream: For output operations.
o ifstream: For file input. Used for
reading data from files and contains open()
method with default input mode. Inherits the get(), getline(), read() functions from
istream.
o ofstream: For file output.Used for writing data to files. Inherits put(), write()
function from ostream
 Usage: These classes provide functionalities to handle different I/O operations.

Page 8 of 23
Stream Class Hierarchy:

Unformatted I/O Operations

 Definition: I/O operations that do not involve formatting, such as get(), put(),
getline().
 Example: get()

#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}

Example: put(): void put() It is a method of cout object and it is used to print the
specified character on the screen or monitor.

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

Page 9 of 23
{
char c=cin.get();
cout.put(c);
//Here it prints the value of variable c; cout.put('c'); //Here it prints the character
'c'; return 0;

Formatted Console I/O Operations

 Definition: I/O operations with specified formatting, using << and >> operators, along with
manipulators. In formatted console input output operations we use built-in functions to
make I/O in perfect alignment.

In C++, there are two ways to perform the formatted IO operations.

 Using the member functions of ios class.


 Using the special functions called manipulators defined in iomanip.h.

Formatted IO using ios class members

The ios class contains several member functions that are used to perform formmated IO
operations.

The ios class also contains few format flags used to format the output. It has format flags
like showpos, showbase, oct, hex, etc. The format flags are used by the function setf( ).

The following table provides the details of the functions of ios class used to perform formatted
IO in C++.

Function Description
width(int) Used to set the width in number of character spaces for the immediate output
data.
fill(char) Used to fill the blank spaces in output with given character.
precision(int) Used to set the number of the decimal point to a float value.
setf(format flags) Used to set various flags for formatting output like showbase, showpos, oct,
hex, etc.
unsetf(format Used to clear the format flag setting.
flags)

All the above functions are called using the built-in object cout.

Lets look at the following code to illustrate the formatted IO operations using member functions
of ios class.

Page 10 of 23
Example - Code to illustrate the formatted IO using ios class

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
cout << "Example for formatted IO" << endl;

cout << "Default: " << endl;


cout << 123 << endl;

cout << "width(5): " << endl;


cout.width(5);
cout << 123 << endl;

cout << "width(5) and fill('*'): " << endl;


cout.width(5);
cout.fill('*');
cout << 123 << endl;

cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;

cout << "setf(showpos): " << endl;


cout.setf(ios::showpos);
cout << 123 << endl;

cout << "unsetf(showpos): " << endl;


cout.unsetf(ios::showpos);
cout << 123 << endl;

return 0;
}

Page 11 of 23
Managing Output with Manipulators

 Definition: Manipulators are used to format output (e.g., std::setw, std::setprecision, fill,
prescision).
 The iomanip.h header file contains several special functions that are used to perform
formmated IO operations.
 The following table provides the details of the special manipulator functions used to
perform formatted IO in C++.

Function Description
setw(int) Used to set the width in number of characters for the immediate output
data.
setfill(char) Used to fill the blank spaces in output with given character.
setprecision(int) Used to set the number of digits of precision.
setbase(int) Used to set the number base.
setiosflags(format flags) Used to set the format flag.
resetiosflags(format Used to clear the format flag.
flags)

Example: Code to illustrate the formatted IO using manipulators

#include <iostream>
#include <fstream>

using namespace std;

Page 12 of 23
void line() {
cout << " " << endl;
}

int main()
{
cout << "Example for formatted IO" << endl;
line();
cout << "setw(10): " << endl;
cout << setw(10) << 99 << endl;
line();
cout << "setw(10) and setfill('*'): " << endl;
cout << setw(10) << setfill('*') << 99 << endl;
line();
cout << "setprecision(5): " << endl;
cout << setprecision(5) << 123.4567890 << endl;
line();
cout << "showpos: " << endl;
cout << showpos << 999 << endl;
line();
cout << "hex: " << endl;
cout << hex << 100 << endl;
line();
cout << "hex and showbase: " << endl;
cout << showbase << hex << 100 << endl;
line();

return 0;
}

Page 13 of 23
User Defined Data Type

A UDT allows users to define their own data types. For example, in a library
management system, we can create a UDT called 'Book' to store information about
books like title, author, genre, etc.

Example:

class Book
{
string title;
string author;
string genre;
public:
void issue();
void return();
void getdata();

Page 14 of 23
};

Class Definition

 Definition: A class is a blueprint for creating objects, encapsulating data and methods.
 Syntax:

class ClassName
{
Access Specifier: //public, protected, private
//properties and methods are declared here

};

Example:
// Class definition
class Book {
private:
string title;
string author;

public:
Book() {}
void setTitle(string newTitle) { title = newTitle; }
void setAuthor(string newAuthor) { author = newAuthor;}
string getTitle() const { return title; }
string getAuthor() const { return author; }
};
Creating objects & Accessing class members
Syntax:
Class_name obj_name;
Ex:
STUDENT sObj;
Syntax to access data members:
object_name.data_member;

Syntax to access member functions:

object_name.function_name(arguments);

Ex:
sObj.accept();

Memory allocation for objects:


When a class is specified, memory space of all the member function is allocated but memory
allocation is not done for the data member. When an object is created, memory allocation for its
Page 15 of 23
data members is done. Therefore, each object has a separate copy of data members and the different
objects share the member functions among them.

Instance Variables

 Definition: Instance variables are the variables defined within a class, representing the
properties of each object created from the class
 Example: In the Car class example, brand and year are instance variables.

Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
Here, myCar is an instance of the Car class, and brand and year are instance variables for that
instance.

Member Methods

 Definition: Functions defined inside a class to operate on class data.


 Example:

void display()
{
std::cout << "Displaying information";
}

Page 16 of 23
Member functions can be defined in two ways
1. Inside the class- when a function is defined inside a class it is treated as INLINE
function.
2. Outside the class (using scope resolution operator ::)
Syntax to define functions outside the class:

Return_type ClassName :: FunName(parameter)


{
//body of funtion
}
Ex:
void STUDENT :: accept(void)
{
cin>>name>>age;
}

Accessing Members

 Syntax: Use the dot operator . for accessing members of an object.


 Example:

Person p;
p.age = 25;
p.display();

Access Specifiers

Access specifiers define the visibility of class members. There are three types:

 Types:
o public: Accessible from outside the class.
o private: Accessible only within the class.
o protected: Accessible within the class and derived classes.

Example:

class Car
{
public:
string brand;
private:
int year;
};

Page 17 of 23
In this example, brand is accessible outside the class, but year is private and can‘t be accessed
directly.

this Pointer

 Definition: An implicit pointer available in member functions, referring to the object


calling the function.
 Usage:

this->data = data;
Example:
class Car {
public:
string brand;
int year;
Car(string brand, int year) {
this->brand = brand;
this->year = year;
}
};
In this example, this->brand refers to the instance variable brand, while brand refers to the
parameter.

Friend Function

 Definition: A function not a member of the class but has access to its private and protected
members. It is defined outside the class. But the function prototype must be inside the class
declaration to make it a friend function.
 Syntax:

friend void display(Person p);


Example:
class Car {
private:
int year;
public:
Car(int y) : year(y) {}
friend void displayYear(Car car);
};

void displayYear(Car car) {


cout << "Year: " << car.year << endl;
}

Here, displayYear is a friend function of the Car class, so it


can access the private member year.

Page 18 of 23
Constructors

 Definition: Special member functions used to initialize objects. It is called when the
object is created.

Example:

class Car {
public:
string brand;
int year;
Car() {
brand = "Unknown";
year = 0;
}
};
Here, Car() is a default constructor that initializes brand and year when an object is created.

 Types:
o Default Constructor: Takes no parameters.
o Parameterized Constructor: Takes parameters to initialize attributes.
o Copy Constructor: Initializes an object using another object of the same class.
 Syntax:

class MyClass {
public:
MyClass() { } // Default
MyClass(int a) { } // Parameterized
MyClass(const MyClass &obj) { } // Copy
};

Examples:
1. Default Constructor:
Car() {
brand = "Unknown";
year = 0;
}
2. Parameterized Constructor:
Car(string b, int y) {
brand = b;
year = y;
}
3. Copy Constructor:
Car(const Car &obj) {
brand = obj.brand;

Page 19 of 23
year = obj.year;
}

Rules and characteristics of constructors in C++:

1. Same Name as the Class

 A constructor must have the same name as the class.


 This allows the compiler to identify it as a constructor.

2. No Return Type

 Constructors do not have a return type—not even void.


 Declaring a return type for a constructor, even void, will cause a compiler error.

3. Automatically Invoked

 Constructors are called automatically when an object of the class is created.


 You do not have to call a constructor explicitly.

4. Can Be Overloaded

 You can have multiple constructors in a class with different parameter lists. This is
known as constructor overloading.
 The correct constructor is chosen based on the arguments provided when the object is
created.
 Example:

class Car {
public:
Car() { } // Default constructor
Car(string b, int y) { } // Parameterized

Destructor

 Definition: Special member function with the same name as the class, preceded by ~
(tilde operator). It is used to release resources allocated to the object. It takes no
arguments.
 Syntax:

~MyClass() { }

Page 20 of 23
Example

class Car {
public:
Car() {
cout << "Car created" << endl;
}
~Car() {
cout << "Car destroyed" << endl;
}
};
In this example, the destructor ~Car() will be called automatically when the Car object goes out
of scope.

Properties of destructors in C++:


1. Same Name as the Class with a Tilde (~)
 The destructor has the same name as the class but is preceded by a tilde (~).
 For example, if the class name is Car, the destructor will be ~Car().
2. No Return Type
 Destructors do not have a return type—not even void.
 Any return type declaration will cause a compilation error.
3. No Parameters (Cannot Be Overloaded)
 Destructors cannot take parameters, which means you cannot overload them.
 Each class can only have one destructor.
4. Automatically Invoked
 Destructors are called automatically when an object goes out of scope, or when delete is
used on a dynamically allocated object.
 You generally don‘t call destructors explicitly.
5. Releases Resources
 Destructors are primarily used for cleanup, such as releasing memory, closing files, or
freeing other resources acquired by the object during its lifetime.

Page 21 of 23
Full program example for the above mentioned concepts:

#include <iostream>
using namespace std;

class Car {
public:
string brand;
int year;

Car(string b, int y) { // Parameterized Constructor


brand = b;
year = y;
}

Car(const Car &obj) { // Copy Constructor


brand = obj.brand;
year = obj.year;
}

void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}

~Car() { // Destructor
cout << "Car destroyed" << endl;
}
};

int main() {
Car car1("Toyota", 2015); // Creating object using parameterized constructor
car1.displayInfo();

Car car2 = car1; // Creating object using copy constructor


car2.displayInfo();

return 0;
}
Output:
Brand: Toyota, Year: 2015
Brand: Toyota, Year: 2015

Page 22 of 23
Car destroyed
Car destroyed

In this example:
 The Car class has a parameterized constructor, a copy constructor, and a destructor.
 We create car1 with the parameterized constructor and car2 with the copy constructor.
 When the program ends, the destructor is called twice, once for each object.

Page 23 of 23
VISION OF THE INSTITUTE

Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.

MISSION OF THE INSTITUTE

To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.

Lecture Notes on Problem Solving using C++ (LTP::3:0:0)


Course Code: DSC12T 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

BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.

Prepared by: Dr. Chandrajit M

Department: Computer Science

Page 1 of 19
Unit 4

Unit-4
Polymorphism: Operator Overloading, Rules for Operator Overloading, 11
Overloading Unary and Binary Operators. Hours
Inheritance: Inheritance, Types of Inheritance, Virtual Functions and Abstract
Classes.
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).

Polymorphism in C++

Polymorphism is the ability of a function, object, or operator to take on multiple forms. It allows
for a more flexible and reusable code.

Polymorphism in C++ can be achieved through two main mechanisms:

1. Compile-time Polymorphism (Static Polymorphism):

 Function Overloading: Defining multiple functions with the same name but different
parameters (either in number or type). The compiler determines which function to call
based on the arguments provided at compile time.
 Operator Overloading: Defining operators (like +, -, <<, >>) to work with user-defined
types.

2. Runtime Polymorphism (Dynamic Polymorphism):

 Virtual Functions: This is the core of runtime polymorphism.


o Functions declared in the base class and overridden (redefined) in the derived
classes.
o Base Class Pointers: Using a pointer or reference of the base class type to access
objects of derived classes.
o Dynamic Dispatch: At runtime, the appropriate function (base or derived) is called
based on the actual type of the object being pointed to.

Operator Overloading

Operator overloading is a type of polymorphism where operators are given a new meaning when
applied to user-defined types (like classes). By overloading an operator, you define how it behaves
for objects of your class.

Page 2 of 19
� To overload an operator, we use a special function called an operator function.

return_type operator op_symbol (argument-list)


{
//body of operator function
}

Here op_symbol is used as the symbol for the operator being overloaded and operator is a keyword.

Steps in Operator Overloading:

 Create a class that defines the data type that is to be used in the overloading operation.
 Declare the operator function in the public part (it can be a friend function too)
 Define the operator function to implement the required operation.

Rules for Operator Overloading

1. Only Existing Operators Can Be Overloaded: You cannot create new operators.
2. Cannot Change Operator Precedence or Associativity: Overloading doesn‘t affect the
precedence of operators.
3. Cannot Overload Certain Operators:
 Sizeof operator
 . Member access operator
 .* pointer to member operator
 :: scope resolution operator
 ?: Conditional operator
4. Syntax: The syntax for operator overloading must follow the syntax rules for the operator
being overloaded.
5. At Least One Operand Must Be a User-Defined Type: You can‘t change the behavior
of operators for built-in types.
6. Unary operators typically do not take parameters when overloaded.
7. Binary operators typically take one parameter for overloading. But those overloaded
using friend function takes one two argument

Overloading Unary Operators (like ++, --, -):


Operate on a single operand. Unary operators typically do not take parameters when overloaded.

Example: Negate a complex numbers by overloading unary (-) operator


#include <iostream>

class Complex {
private:
double real;
double imag;

Page 3 of 19
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// Overloading the unary negation operator


Complex operator-() const {
return Complex(-real, -imag);
}

void display() const {


std::cout << real << " + " << imag << "i" << std::endl;
}
};

int main() {
Complex c1(2, 3);
Complex c2 = -c1; // Using the overloaded unary negation operator

c1.display(); // Output: 2 + 3i
c2.display(); // Output: -2 - 3i

return 0;
}

Overloading Binary Operators:


Binary Operators (like +, -, *, /): Operate on two operands. Binary operators typically take one
parameter for overloading.

Example: Add two complex numbers by Overloading “+” operator

#include <iostream>
using namespace std;
class Complex
{
private:
float real, imag;
public:
Complex(float r = 0, float i = 0)
{
real=r;
imag=i;

Page 4 of 19
}

// Overload + operator to add two Complex objects


Complex operator + (Complex obj)
{
return Complex(real + obj.real, imag + obj.imag);
}

void display() const


{
cout << real << " + " << imag << "i" << endl;
}
};

int main()
{
Complex c1(2, 3), c2(1.5, 2.5);
Complex c3 = c1 + c2; // Using overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}
Output:
3.5 + 5.5i

Inheritance in C++
Inheritance allows one class (derived class) to acquire properties and behavior from another class
(base class). It supports code reuse and polymorphism. It allows us to create a new class (derived
class) from an existing class (base class). The derived class inherits the features from the base class
and can have additional features of its own. Inheritance is an is-a relationship. We use inheritance
only if an is-a relationship is present between the two classes. Here are some examples: A car is a
vehicle, Orange is a fruit.

Types of Inheritance
1. Single Inheritance: A derived class inherits from a single base class.
2. Multiple Inheritance: A derived class inherits from more than one base class.
3. Multilevel Inheritance: A class is derived from a class which is also derived from
another class.
4. Hierarchical Inheritance: Multiple classes inherit from a single base class.
5. Hybrid Inheritance: Combination of two or more types of inheritance.

Page 5 of 19
The Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
Example:
class Base {
.... ... ....
};

class Derived : public Base {


.... ... ....
};

Page 6 of 19
Example for Single Inheritance:
#include <iostream>
using namespace std;

// Base class
class Windows10 {
public:
void boot() {
cout << "Booting Windows 10..." << endl;
}
};

// Derived class
class Windows11 : public Windows10 {
public:
void newFeature() {
cout << "Welcome to Windows 11 with new features!" << endl;
}
};

int main() {
Windows11 myWindows11;

// Using methods from both base and derived classes


myWindows11.boot(); // Inherited from Windows10
myWindows11.newFeature(); // Defined in Windows11

return 0;
}
Output:
Booting Windows 10...
Welcome to Windows 11 with new features!

This example illustrates single inheritance where Windows11 inherits functionality from
Windows10, showcasing how derived classes can build upon the base class functionality.

Page 7 of 19
Example for Multilevel Inheritance:
#include <iostream>
using namespace std;

// Base class
class Windows10 {
public:
void boot() {
cout << "Booting Windows 10..." << endl;
}
};

// Derived class from Windows10


class Windows11 : public Windows10 {
public:
void newFeature() {
cout << "Welcome to Windows 11 with new features!" << endl;
}
};

// Derived class from Windows11


class Windows12 : public Windows11 {
public:
void latestFeature() {
cout << "Enjoying the latest features in Windows 12!" << endl;
}
};

int main() {
Windows12 myWindows12;

// Using methods from all three classes


myWindows12.boot(); // Inherited from Windows10
myWindows12.newFeature(); // Inherited from Windows11
myWindows12.latestFeature(); // Defined in Windows12

return 0;
}
Output:
Booting Windows 10...

Page 8 of 19
Welcome to Windows 11 with new features!
Enjoying the latest features in Windows 12!

This example demonstrates multilevel inheritance, where Windows12 inherits functionality


from Windows11, which in turn inherits from Windows10. Each class adds its own features
while also retaining the functionality of the classes it derives from.

Example for Multiple Inheritance:


#include <iostream>
using namespace std;

// Base class 1
class Windows {
public:
void bootWindows() {
cout << "Booting Windows environment." << endl;
}
};

// Base class 2
class Linux {
public:
void bootLinux() {
cout << "Booting Linux environment." << endl;
}
};

// Derived class from both Windows and Linux


class NewOS : public Windows, public Linux {
public:
void bootNewOS() {
cout << "Booting NewOS with features of both Windows and Linux." << endl;
}
};

int main() {
NewOS myOS;

// Using methods from both base classes and the derived class
myOS.bootWindows(); // Inherited from Windows

Page 9 of 19
myOS.bootLinux(); // Inherited from Linux
myOS.bootNewOS(); // Defined in NewOS

return 0;
}
Output:
Booting Windows environment.
Booting Linux environment.
Booting NewOS with features of both Windows and Linux.

This example demonstrates multiple inheritance in C++, where the NewOS class inherits
features from both Windows and Linux classes.

Example for Hierarchical Inheritance:


#include <iostream>
using namespace std;

// Base class
class Windows {
public:
void boot() {
cout << "Booting Windows..." << endl;
}
};

// Derived class for Windows 7


class Windows7 : public Windows {
public:
void displayVersion() {
cout << "This is Windows 7." << endl;
}
};

// Derived class for Windows 8


class Windows8 : public Windows {
public:
void displayVersion() {
cout << "This is Windows 8." << endl;
}
};

Page 10 of 19
// Derived class for Windows 10
class Windows10 : public Windows {
public:
void displayVersion() {
cout << "This is Windows 10." << endl;
}
};

int main() {
Windows7 win7;
Windows8 win8;
Windows10 win10;

// Using methods from base and derived classes


cout << "For Windows 7:" << endl;
win7.boot();
win7.displayVersion();

cout << "\nFor Windows 8:" << endl;


win8.boot();
win8.displayVersion();

cout << "\nFor Windows 10:" << endl;


win10.boot();
win10.displayVersion();

return 0;
}
Output:
For Windows 7:
Booting Windows...
This is Windows 7.

For Windows 8:
Booting Windows...
This is Windows 8.

For Windows 10:


Booting Windows...

Page 11 of 19
This is Windows 10.

This example demonstrates hierarchical inheritance, where multiple classes (Windows7,


Windows8, and Windows10) inherit from a common base class Windows. Each derived class has
its own unique behavior through the displayVersion() method, while sharing the common
functionality of boot() from the Windows base class.

Example for Hybrid Inheritance:


#include <iostream>
using namespace std;

// Base class
class OperatingSystem {
public:
void boot() {
cout << "Booting Operating System..." << endl;
}
};

// Derived class from OperatingSystem


class Windows : public OperatingSystem {
public:
void displayWindowsVersion() {
cout << "This is a Windows operating system." << endl;
}
};

// Derived class from OperatingSystem


class Linux : public OperatingSystem {
public:
void displayLinuxVersion() {
cout << "This is a Linux operating system." << endl;
}
};

// Derived class from both Windows and Linux


class NewOS : public Windows, public Linux {
public:
void displayNewOSFeatures() {
cout << "This is NewOS with features from Windows and Linux." << endl;

Page 12 of 19
}
};

int main() {
NewOS myOS;

// Using methods from both base and derived classes


myOS.boot(); // From OperatingSystem
myOS.displayWindowsVersion(); // From Windows
myOS.displayLinuxVersion(); // From Linux
myOS.displayNewOSFeatures(); // From NewOS

return 0;
}
Output:
Booting Operating System...
This is a Windows operating system.
This is a Linux operating system.
This is NewOS with features from Windows and Linux.

This example illustrates hybrid inheritance where the NewOS class derives features from both
Windows and Linux, which in turn derive from a common base class OperatingSystem. This
structure allows NewOS to combine functionalities from multiple sources effectively.

Deriving Class with Different access modes:


In C++ inheritance, we can derive a child class from the base class in different access/visibility
modes. The visibility mode specifies whether the features of the base class are publicly or privately
or protected inherited. It can be public or private or protected.


public inheritance makes public members of the base class public in the derived class, and
the protected members of the base class remain protected in the derived class.
 protected inheritance makes the public and protected members of the base
class protected in the derived class.
 private inheritance makes the public and protected members of the base class private in the
derived class.
Note: private members of the base class are inaccessible to the derived class.

Page 13 of 19
Scope/Accessing Members during Inheritance:

Exmaple:
class Base {
public:
int x;
protected:
int y;
private:
int z;
};

class PublicDerived: public Base {


// x is public
// y is protected
// z is not accessible from PublicDerived
};

class ProtectedDerived: protected Base {


// x is protected
// y is protected
// z is not accessible from ProtectedDerived
};

Page 14 of 19
class PrivateDerived: private Base {
// x is private
// y is private
// z is not accessible from PrivateDerived
};

Virtual Functions

 Virtual Functions: Used in a base class to allow derived classes to override it. Virtual
functions enable runtime polymorphism.
 Pure Virtual Functions: A pure virtual function is a virtual function that has no definition
within the class. A pure virtual function is a "do nothing"/empty function. Here "do
nothing" means that it just provides the template, and derived class implements the
function. A class having pure virtual function cannot be used to create direct objects of its
own. Example: virtual void f() = 0;

Example for Virtual function to show the dynamic binding(run time polymorphism):

#include <iostream>
using namespace std;

class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};

class Derived : public Base {


public:
void print(){
cout << "Derived Function" << endl;
}
};

int main() {
Derived derived1;

// pointer of Base type that points to derived1


Base* base1 = &derived1;

Page 15 of 19
// calls member function of Derived class
base1->print();

return 0;
}
Output:

Derived Function

Abstract Classes

A class with at least one pure virtual function (i.e., virtual void func() = 0;). Objects cannoted be
created for abstract class and serves only as a base class.

Example:

class Shape {

public:

virtual void draw() = 0; // Pure virtual function

};

Page 16 of 19
File Handling in C++

File handling involves storing and retrieving data to and from files using file streams. C++ provides
classes and functions for handling file I/O.

File Opening Modes

 ios::in: Open for reading.

 ios::out: Open for writing.

 ios::app: Append to the end of the file.

 ios::binary: Open in binary mode.

 ios::trunc: If the file exists, its contents are truncated.

 ios::ate: Go to the end of the file on opening.

Classes for File Stream Operations

In C++, file stream operations are primarily handled through the standard library, specifically using
the <fstream> header. This header provides several classes that allow you to work with files in a
convenient and efficient way. Here‘s an overview of the main classes for file stream operations:

1. fstream

 Description: The fstream class is used for both input and output file operations. It allows
you to read from and write to a file using the same object.

 Usage: It is suitable for cases where you want to read from and write to the same file.

Example:

fstream myfile(―example.txt‖, ios::in | ios::out | ios::app);

or

fstream myfile;
myfile.open("example.txt", ios::in | ios::out | ios::app);
2. ifstream

 Description: The ifstream class is used specifically for input file operations. It allows you
to read data from a file.

 Usage: It is ideal for cases where you only need to read data from a file.

Example: ifstream infile("example.txt"); // Open file for reading

Page 17 of 19
3. ofstream

 Description: The ofstream class is used specifically for output file operations. It allows
you to write data to a file.

 Usage: It is ideal for cases where you only need to write data to a file.

Example: ofstream outfile("output.txt"); // Open file for writing

File I/O Operations

1. Opening a File
ofstream outfile;
outfile.open("example.txt", ios::out);

2. Writing to a File
if (outfile.is_open()) {
outfile << "Hello, World!" << endl;
outfile.close();
}
3. Reading from a File
ifstream infile("example.txt");
string line;
if (infile.is_open()) {
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
}
4. Appending to a File
ofstream outfile("example.txt", ios::app);
if (outfile.is_open()) {
outfile << "Appending this text." << endl;
outfile.close();
}
5. Closing a File: Always close files after performing file operations to avoid resource leaks.
inFile.close();

Page 18 of 19
Example for reading and writing operations on file:
#include <iostream>
#include <fstream>
using namespace std;

int main() {
// Write to file
ofstream outFile("sample.txt");
if (outFile.is_open()) {
outFile << "Writing to file." << endl;
outFile.close();
}

// Read from file


ifstream inFile("sample.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}

return 0;
}
Note:This program opens a file named sample.txt, writes a line to it, closes the file, then
reopens it to read and print the contents.

Page 19 of 19

You might also like