C++ 10marka
C++ 10marka
UNIT I
1. Explain about the basic concepts and benefits of OOP’s
○ Class & Object
○ Encapsulation
○ Data Abstraction
○ Inheritance
○ Polymorphism
○ Message Passing
Class
● A class is a template that unites data and operations
● A class is an abstract of the real world entities with similar properties
● A class identifies a set of similar objects
● Ideally, the class is an implementation of abstract data type(ADT)
● A class contains data members / attributes
● A class has operations / member functions / methods
● The class offers data abstraction and encapsulation of Object Oriented Programming
● A class is defined by a keyword class
class Account
{
private:
char Name[20];
int AccountType;
int AccountNumber;
float Balance;
// data member
public:
Deposit();
Withdraw();
Enquire();
//member function
};
Object:
● Object is the instance of the class
● A object comprises data members and member functions
● Data members of an object can be accessed by dot operator
● Member functions are invoked by dot operator
Example
Account acc1, acc2;
Two objects (acc1, acc2) are created for Account class
Data abstraction:
Data abstraction is creating new data types that are well suited to an application
Example:
Account
Date
Complex
data
function
Inheritance
● Inheritance allows the extension and reuse existing code without having to rewrite the
code
● Inheritance involves the creation of new classes (derived classes) from the existing one
(base class)
● This enables the creation of a hierarchy of classes
C++ supports the following inheritances
1. Single
2. Multiple
3. Multi level
4. Hierarchy
5. Hybrid
Polymorphism:
Polymorphism allows a single name or operator to be associated with different operations
depending on the data type
C++ provides three types of Polymorphism
1. Function Overloading
2. Operator Overloading
3. Virtual function (dynamic binding)
Message Passing
Message passing is the process of invoking an operation on an object
Example:
acc1.withdraw();
acc1.deposit();
acc1.balance();
2. Explain various control structures in C++
Control Structures is used to transfer the control of the program.
Branching Statement:
● if statement
● if - else statement
● switch statement
● goto statement
Looping Statement:
● for statement
● while statement
● do - while statement
Simple if statement
The if statement is a decision making statement in which if the condition is true, statements
inside the if is executed
Syntax:
if ( condition )
{
statement(s);
}
Example:
big = a;
if ( b > big )
{
big = b;
}
In if else Statement, if the condition is true, block or statement after the if condition is executed
otherwise else block or statement is executed
Syntax:
if ( condition )
{
statement(s);
}
else
{
statement(s);
}
Example:
if( a > b)
big = a;
else
big = b;
for Loop:
for statement is used to execute a statement or group of statement one or more times
Syntax:
for( expression1; expression2; expression3)
{
statement(s);
}
● expression1 - initialization
● expression2 - Condition
● expression3 - Increment / Decrement
Examples
for(i = 1; i <= 10; i++)
cout<<i<<”\t”;
prints 1 to 10
While Loop
The while loop is similar to the for loop, used to execute the statement or block of statements one
or more times
Syntax:
expression1;
while( expression2)
{
statement(s);
expression3;
}
Examples:
i = 1;
while( i <= 10)
{
cout<<i<<”\t”;
i = i + 1;
}
do while:
do while is used only when the loop must be executed at least once if condition becomes false
Syntax:
expression1;
do
{
statement(s);
expression3;
} while( expression2 );
Example:
do
{
cin>>choice;
---------
---------
}while(choice < 4);
C++ operators are special characters which instruct the compiler to perform operation on some
operands.
1. Unary operator have single operand
2. Binary operator have two operands
Operators
Operators supported by C++
● Arithmetic operators
● Relational operators
● Logical operators
● Assignment operators
● Increment and Decrement operators
● Conditional operators
● Bitwise operators
● Special operators
Arithmetic Operator:
Arithmetic operators are used to perform arithmetic operation
Operator Purpose
* Multiplication
/ Division
% Modulo
Relational Operator:
● Relational operators is used to compare values.
● Relational operators are binary operators
● The comparison yields an integer value
● It evaluates to zero if the condition is false, otherwise non zero value
Operator Purpose
== Equal to
!= Not equal to
Logical Operator:
Logical operators are useful in combining one or more conditions.
Operator Purpose
|| Logical OR
! Logical NOT
Assignment Operator:
Assignment operator is used to assign a value to the variable.
variable = expression
n = 50;
x = x + 1;
Example:
big = a > b ? a : b;
small = a < b ? a : b;
Bitwise Operator:
Operator Purpose
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
Complement (~)
It is used to complement the content of the variable. ( Zero’s are converted into One’s and
One’s are converted into Zero’s )
Special Operator:
sizeof
sizeof operator returns the size of the data type
comma operator
A set of expressions separated by comma is a valid construct in C++.
Example:
i = ( j = 3, j + 2 );
t = x, x = y, y = t;
UNIT II
1. Explain about types of constructors with suitable examples.
Constructor
● A class in C++ may contain two special member functions dealing with internal
workings of a class
● These functions are
○ constructor
○ destructor
● A constructor enables an object to initialize itself during creation
● It is also called as object initialization
● A destructor destroys the objects when it is no longer required, by releasing all the
resources allocated to it
● It is also called as cleanup
● A Constructor is a special member function whose main operation is to allocate the
required resources such as memory
● Constructor is used to initialize the members of the object
● A constructor function has the same name of the class
● It is executed automatically when object is created
● It is used to initialize object member parameters and allocate necessary resources to the
object members
● The constructor has no return type
Syntax:
class class_name
{
…….. // private member
public:
class_name()
{
// object initialization
}
};
Example:
class A
{
private:
int a;
public:
A()
{
a = 0;
}
…………….
};
Parameterized Constructor:
● Constructor can be invoked with arguments as normal functions
● The argument list is specified inside the bracket
● Constructor with arguments are called as parameterized constructor
class A
{
private:
int a;
public:
A() { a = 0; }
A(int x)
{
a = x;
}
…………….
};
Copy Constructor:
● The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously.
● copy constructor is used to initialize one object from another of the same type.
class A
{
private:
int a;
public:
………………...
A(A& obj)
{
a = obj.a;
}
…………….
};
Destructor:
Destructor is a special member function
It is invoked (called) when the object is destroyed
The name of the destructor is same name of the class preceded with ~ (~classname)
class A
{
private:
int a;
public:
………………...
~A()
{
cout<<”object destroyed”;
}
…………….
};
2. Explain in detail about Operator Overloading in C++.
Operator Purpose
:: Scope resolution
?: Conditional
.* Pointer to member
Example:
class Index
{
private:
int index;
public:
Index() { index = 0; }
int getindex() { return index;}
void operator++()
{
index = index + 1;
}
void operator--()
{
index = index - 1;
}
};
int main()
{
Index obj;
cout<<”index = “<<obj.getindex()<<”\n”;
++obj;
++obj;
cout<<”index = “<<obj.getindex()<<”\n”;
--obj;
cout<<”index = “<<obj.getindex()<<”\n”;
return 0;
}
Binary Operator Overloading
Syntax
return_type operator operator symbol(arg)
1. First object is taken as implicit operand and second operand must be passed explicitly
2. The first object data members are accessed without dot operator, second operator objects
are accessed with dot operator
Example:
complex obj1(5,7);
complex obj2(12,8);
complex obj3;
obj3 = obj1 + obj2;
3. Explain in detail about Operator Overloading using the friend function in C++.
Example:
class Index
{
private:
int index;
public:
Index() { index = 0; }
int getindex() { return index;}
friend void operator++(Index &);
};
int main()
{
Index obj;
cout<<”index = “<<obj.getindex()<<”\n”;
++obj;
cout<<”index = “<<obj.getindex()<<”\n”;
return 0;
}
class complex
{ int real; int imag;
public:
complex() : real(0), imag(0) {}
complex(int x, int y): real(x), imag(y){}
complex(complex obj)
: real(obj.real), imag(obj.imag) {}
friend complex operator +(complex obj1,
complex obj2) ;
void print()
{
cout<< real << “ + “
<< imag << “i\n”;
}
};
The capability of a class to derive properties and characteristics from another class is called
Inheritance.
Inheritance is one of the most important feature of Object Oriented Programming.
Derived Class:
The class that inherits properties from another class is called Sub class or Derived Class.
Base Class:
The class whose properties are inherited by sub class is called Base Class or Super class.
Modes of Inheritance
Public mode:
If we derive a sub class from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become
protected in derived class.
class B : public A { … }
Protected mode:
If we derive a sub class from a Protected base class. Then both public member and protected
members of the base class will become protected in derived class.
class B : protected A { … }
Private mode:
If we derive a sub class from a Private base class. Then both public member and protected
members of the base class will become Private in derived class.
class B : private A { … }
Single Inheritance
In single inheritance, a class is allowed to inherit from only one class. i.e. one derived class is
inherited by one base class only.
● A derived class may begin its with a copy of its base class members
● A derived class inherits data members and member functions
● The class B derived from class A
● Derivation of a class from only
class A
{
…..
};
class B : public A
{
…..
};
Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e
one sub class is inherited from more than one base classes.
Derivation of a class from two or more base classes is called multiple inheritance
class A
{
…..
};
class B
{
…..
};
class C : public A, public B
{
…..
};
In the Multilevel inheritance, a derived class will inherit a base class and as well as the derived
class also act as the base class to other class.
For example, three classes called A, B, and C, as shown in the below image, where class C is
derived from class B and class B, is derived from class A. In this situation, each derived class
inherit all the characteristics of its base classes. So class C inherits all the features of class A and
B.
class A
{
…..
};
class B : public A
{
…..
};
class C : public B
{
…..
};
In the above example, Class B derives from Class A and Class C derives from Class B
Hierarchical Inheritance:
In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more
than one derived class is created from a single base class.
Derivation of several classes from a single class is called hierarchical inheritance
class A
{
…..
};
class B : public A
{
…..
};
class C : public A
{
…..
};
class D : public A
{
…..
};
In the above example class A acts base class for Class B, C and D
Hybrid Inheritance:
Hybrid Inheritance is implemented by combining more than one type of inheritance.
class A
{
….
};
class B : A
{
….
};
class C : A
{
….
};
class D : B, C
{
….
};
5. Discuss about Polymorphism.
Runtime polymorphism
class Father
{
string name;
public:
Father(string n) : name(n){}
virtual void print()
{
cout<<"Father name " << name <<"\n";
}
};
class Son : public Father
{
string name;
public:
Son(string fname, string sname) : Father(fname), name(sname){}
void print()
{
cout<<"Son name " << name << "\n";
}
};
int main()
{
Father f("Siva");
Son s("Siva","Ganapathy");
Father *ptr;
ptr = &f;
ptr->print();
ptr = &s;
ptr->print();
return 0;
}
In the above program, the base class has a print function and the derived class has a print
function. Based on the assigned class the function class decides the function to call in the
run-time
Unit III
1. Explain the classes for file stream operations.
File:
A program involves data communication
1. Between the console and the program or
2. Between the files and the program or
3. Even both
The program must at least perform data exchange between processor and main memory
File Stream:
● The streams computation model for manipulating files resemble the console streams
model
● It uses file streams as a means of communication between the programs and the data files
● The input stream supplies data to the program
● The input stream extracts the data from the file and supplies it to the program
● The output stream receive data from the program
● The output stream stores the data into the file supplied by the program
The file handling techniques of C++ support file manipulation in the form of stream objects
There are no predefined objects for disk files
All class declaration have to be done explicitly in the program
There are three classes for handling files:
1. ifstream - for handling input files
2. ofstream - for handling output files
3. fstream - for handling files on which both input and output can be performed
The classes ifstream, ofstream and fstream are defined in fstream.h
filebuf:
● class filebuf sets the file buffer to read and write
● It contains constant openprot used in open() of file stream class
● It also contains close() as a member
fstreambuf:
● class fstreambuf supports operations common to the file streams
● It serves as a base class for the derived classes ifstream, ofstream and fstream
● It contains open() and close() as a member functions
ifstream:
● class ifstream supports input operations
● It contains open() with default input mode and inherits get(), getline(), read(), seekg() and
tellg() functions from istream
ofstream:
● class ofstream supports output operations
● It contains open() with default output mode and inherits put(), seekp(), tellp() and write()
functions from ostream
fstream:
● class fstream supports simultaneous input and output operations
● It contains open() with default input mode
● It inherits all the functions from istream and ostream classes through iostream
● Opening a file in ios::out mode also opens it in the ios::trunc mode by default. If the file
already exists, it is truncated
● Both ios::app and ios::ate sets pointers to the end of file, but they differ in terms of the
types of operations permitted on a file
● The ios::app allows to add data from the end of file
● The ios::ate mode allows to add or modify the existing data anywhere in the file
● In both cases, a file is created if it is non - existed
● The mode ios::app can be used only with output files
● The stream classes ifstream and ofstream open files in read and write modes respectively
by default
● For fstream class, the mode parameter must be explicitly passed
● More than one value may be ORed to have a combined effect
istream in_file( “myfile”, ios::in | ios::binary )
Unit IV
1. Explain Stack and its Operations.
STACK
Stack is a linear data structure in which items are added or removed only at one end, called top
of the stack. Thus, there is no way to add or delete elements anywhere else in the stack. A stack
is based on Last-In-First-Out (LIFO) principle.
Stack of Plate
STACK OPERATIONS
There are two key operations associated with the stack data structure: push and pop. Adding an
element to the stack is referred as push operation while reading or deleting an element from the
stack is referred as pop operation.
Push
Pop
The pop operation involves the following subtasks:
1. Retrieving or removing the element at the top of the stack.
2. Decrementing the stack pointer, top.
Algorithm pop(element)
Step 1: Start
Step 2: If top = -1 goto Step 3 else goto Step 4
Step 3: Display message ”Stack Empty” and exit
Step 4: Return stack[top] and set top = top - 1
Step 5: Stop
QUEUE
Queue is a linear data structure in which items are inserted at one end called ‘Rear’ and deleted
from the other end called ‘Front’. Queues are based on the First-In-First-Out (FIFO) principle
that means the data item that is inserted first in the queue is also the first one to be removed from
the queue.
Queue
Logical Representation of Queue
Queues appear as a group of elements stored at contiguous locations in memory. Each successive
insert operation adds an element at the rear end of the queue while each delete operation removes
an element from the front end of the queue. The location of the front and rear ends are marked by
two distinct pointers called front and rear.
There are two key operations associated with the queue data structure:
1. insert
2. delete
The insert operation adds an element at the rear end of the queue while the delete operation
removes an element from the front end of the queue.
Insertion
Deletion
Insert
The insert operation involves the following subtasks:
(a) Receiving the element to be inserted.
(b) Incrementing the queue pointer, rear.
(c) Storing the received element at new location of rear.
The insert operation involves checking whether or not the queue pointer rear is pointing at the
upper bound of the array. If it is not, rear is incremented by 1 and the new item is added at the
end of the queue.
Algorithm insert(element)
Step 1: Start
Step 2: If front = NULL goto Step 3 else goto Step 6
Step 3: front = rear = 0
Step 4: queue[front]=element
Step 5: Goto Step 10
Step 6: if rear = MAX-1 goto Step 7 else goto Step 8
Step 7: Display the message, “Queue is Full” and goto Step 10
Step 8: rear = rear +1
Step 9: queue[rear] = element
Step 10: Stop
Delete
The delete operation involves the following subtasks:
1. Retrieving or removing the element from the front end of the queue.
2. Incrementing the queue pointer, front, to make it point to the next element in the queue.
The delete operation involves checking whether or not the queue pointer front is already pointing
at NULL (empty queue). If it is not, the item that is being currently pointed is removed from the
queue (array) and the front pointer is incremented by 1.
Algorithm delete()
Step 1: Start
Step 2: If front = NULL and rear = NULL goto Step 3 else goto Step 4
Step 3: Display the message, “Queue is Empty” and goto Step 10
Step 4: if front != NULL and front = rear goto Step 5 else goto Step 8
Step 5: Set i = queue[front]
Step 6: Set front = rear = -1
Step 7: Return the deleted element i and goto Step 10
Step 8: Set i = queue[front]
Step 9: Return the deleted element i
Step 10: Stop
INFIX
Example:
a+b
POSTFIX
Example
ab+
PREFIX
+ab
Example:
5x2 + 4x + 2
Each term in the polynomial expression has two parts:
1. Coefficient part
2. Exponential part
In the term 5x2
3 is the coefficient part and
2 is the exponential part
The terms in the polynomial expression can be represented using a linked list node with three
parts as follows
5 2 Link
5x2 + 4x + 2 and
5x + 5
5x2 + 9x + 7
Unit V
Tree Traversal
1. Preorder
2. Inorder
3. Postorder
1. Preorder
In the preorder traversal the left node is visited first , then the root node is visited and finally the
right node is visited.
Algorithm:
The preorder traversal method performs the following operations:
(a) Process the root node (N).
(b) Traverse the left subtree of N (L).
(c) Traverse the right subtree of N (R).
2. Inorder
In the preorder traversal the root node is visited first, then the left node is visited and finally the
right node is visited.
Algorithm:
The inorder traversal method performs the following operations:
(a) Traverse the left subtree of N (L).
(b) Process the root node (N).
(c) Traverse the right subtree of N (R).
3. Postorder
In the postorder traversal the left node is visited and the right node is visited and finally the right
node is visited
Algorithm:
The postorder traversal method performs the following operations:
(a) Traverse the left subtree of N (L).
(b) Traverse the right subtree of N (R).
(c) Process the root node (N).
GRAPH TRAVERSAL
One of the common tasks associated with graphs is to traverse or visit the graph nodes and edges
in a systematic manner. There are two methods of traversing a graph:
1. Breadth First Search (BFS)
2. Depth First Search (DFS)
The BFS traversal sequence for the above graph will be: v1 , v2 , v3 , v4 , v5 , v6 , v7 , v8 .
Algorithm BFS()
Step 1: Start
Step 2: Set status[] = 1
Step 3: Push(queue, v1)
Step 4: Set status[v1]=2
Step 5: Repeat Step 6–11 while queue[] is not empty
Step 6: V = Pop(queue)
Step 7: status[V]=3
Step 8: Repeat Step 9-11 while adj(V) is not empty
Step 9: If adj(V) = 1 goto step 10 else goto step 8
Step 10: Push(queue, adj(V))
Step 11: Set adj[v]=2
Step 12: Stop
Algorithm DFS()
Step 1: Start
Step 2: Set status[] = 1
Step 3: Push(stack, v1)
Step 4: Set status[v1]=2
Step 5: Repeat Step 6–11 while stack[] is not empty
Step 6: V = Pop(stack)
Step 7: status[V]=3
Step 8: Repeat Step 9-11 while adj(V) is not empty
Step 9: If adj(V) = 1 goto step 10 else goto step 8
Step 10: Push(stack, adj(V))
Step 11: Set adj[v]=2
Step 12: Stop
Applications
● Google Maps
● Road Networks
● Logistics Research
It is important to note the following points regarding Dijkstra Algorithm-
Algorithm: