0% found this document useful (0 votes)
3 views43 pages

C++ 10marka

The document covers fundamental concepts of Object-Oriented Programming (OOP) including classes, objects, encapsulation, inheritance, polymorphism, and message passing. It explains control structures in C++, various operators, types of constructors, operator overloading, and inheritance types with examples. Each section provides definitions, syntax, and practical examples to illustrate the concepts effectively.

Uploaded by

thorodinsob19
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)
3 views43 pages

C++ 10marka

The document covers fundamental concepts of Object-Oriented Programming (OOP) including classes, objects, encapsulation, inheritance, polymorphism, and message passing. It explains control structures in C++, various operators, types of constructors, operator overloading, and inheritance types with examples. Each section provides definitions, syntax, and practical examples to illustrate the concepts effectively.

Uploaded by

thorodinsob19
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/ 43

10 Mark Questions

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 Hiding or Encapsulation


Grouping the data and function into a single unit is called as Encapsulation
Example

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

for(i = 1; i <= n; i++)


cout<<i<<”\t”;
prints 1 to n

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);

3. Explain various operators in C++

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

+ Addition or Unary plus

- Subtraction or Unary Minus

* 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

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

To check eligibility for voting


age >= 18
age > 17

To check the given number is zero


x == 0
To check the given number is negative
x<0
To check the given number is positive
x>0

Logical Operator:
Logical operators are useful in combining one or more conditions.

Operator Purpose

&& Logical AND

|| Logical OR

! Logical NOT

To check the given value is in range 50 - 60


( x >= 50 ) && ( x <= 60)

To check given character is vowel


( ch == ‘a’) ||( ch == ‘e’) ||( ch == ‘i’) ||( ch == ‘o’) ||( ch == ‘u’)

To check given value is non zero


!(x == 0)

Increment / Decrement Operators:


● ++ and -- are increment and decrement operators.
● ++ is used to increment variable value by 1
● x++ is equivalent to x = x + 1;
● -- is used to decrement variable value by 1
● x-- is equivalent to x = x - 1
x++ Post increment

++x Pre increment

x-- Post decrement

--x Pre decrement

Assignment Operator:
Assignment operator is used to assign a value to the variable.
variable = expression

n = 50;

area = length * breadth;

x = x + 1;

Conditional Operator (Ternary Operator)

It is the alternative for the if else statement


Syntax:
expression1 ? expression2 : expression3

Example:
big = a > b ? a : b;
small = a < b ? a : b;

Bitwise Operator:

Bitwise Operator is used to perform bit level operation on variables

Operator Purpose

& Bitwise AND

| Bitwise OR

^ Bitwise XOR
~ Bitwise Complement

<< Shift Left

>> Shift Right

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 )

Left Shift Operator:


c = a << 3;
The bits in the variable a is shifted 3 digits left and stored in c.

Right Shift Operator:


c = a >> 2;
The bits in the variable a is shifted 2 digits right and stored in c.

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;
}
…………….
};

A constructor has the following characteristics


● It has the same name of the class
● It is executed automatically when the object is created
● It does not have any return type
● It is used to initialize the data members of a class
● It is also used to allocate memory for dynamic data type
● A constructor without argument is called as default constructor

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 overloading features of C++ achieves polymorphism


● Polymorphism is derived from the greek words poly and morphism
● poly refers to many or multiple
● morphism refers to actions
● Performing many actions with a single operator

The operator overloading can be applied to


1) Extend capability of operator to operate on user defined data type
2) Data conversion

Operator Purpose

. Member access (dot operator)

:: Scope resolution

?: Conditional

.* Pointer to member

sizeof size of data type

Operator overloading using member function:

Unary Operator overloading

operator keyword used to overload in c++


return_type operator operator symbol (arguments)

return_type - return type of the operator


operator - keyword
operator symbol - operator to be overloaded
arguments - arguments for the operator (optional)
Steps in Operator overloading
1. Create a class
2. Declare and define an operator function (friend function), in public part of the class
3. Create an object and invoke operator

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)

operator symbol - operator to be overloaded


arg - second operand for the binary operator

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 operator +(complex obj)


{
complex t;
t.real = real + obj.real;
t.imag = imag + obj.imag;
return t;
}

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++.

● Operator overloading features of C++ achieves polymorphism


● Polymorphism is derived from the greek words poly and morphism
● poly refers to many or multiple
● morphism refers to actions
● Performing many actions with a single operator
Operator overloading using friend function:

● Friend function operator overloading overcomes some limitation of member function


operator overloading
● It allows overloading of stream operators( << or >> ) for stream computation
● Friend function requires the arguments to be explicitly passed to the function
friend return_type operator operator symbol(arg1 [,arg2])

Unary Operator Overloading using friend function

friend return_type operator operator symbol(arg1)

The operator function is declared as friend function in the class


The class object is passed as argument

Example:

class Index
{
private:
int index;
public:
Index() { index = 0; }
int getindex() { return index;}
friend void operator++(Index &);
};

void operator++(Index &obj)


{
obj.index = obj.index + 1;
}

int main()
{
Index obj;
cout<<”index = “<<obj.getindex()<<”\n”;
++obj;
cout<<”index = “<<obj.getindex()<<”\n”;
return 0;
}

Binary Operator Overloading using friend function

friend return_type operator operator symbol(arg1, arg2)

The operator function is declared as friend function in the class


The class object is passed as arguments

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”;
}
};

complex operator + (complex obj1, complex obj2)


{
complex t;
t.real = obj1.real + obj2.real;
t.imag = obj1.imag + obj2.imag;
return t;
}
int main()
{
complex obj1(5,7);
complex obj2(12,8);
complex obj3;
obj3 = obj1 + obj2;
obj3.print();
return 0;
}
4. Define inheritance. Explain with examples the various types of inheritance.

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 above example, Class C derives from Class A and B

Multi level Inheritance:

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.

● Polymorphism means having many forms


● Polymorphism is the ability of a message to be displayed in more than one form
● In C++, Polymorphism can be achieved by two ways
○ Compile Time
○ Run Time
● Compile time polymorphism is also called as static binding or early binding
● Run time polymorphism is also called as dynamic binding or late binding

Compile time polymorphism


In compile time polymorphism, the compiler knows the complete information about the
functions, such as
● return type
● number of operands
Function overloading and operator overloading falls under the category of compile time
polymorphism

int add(int a, int b)


{
return a + b;
}

float add(float a, float b)


{
return a + b;
}
int main()
{
cout << “Integer Addition\n”;
cout<<add(5,10);
cout<< “Float Addition\n”;
cout<<add(5.0f, 21.35f);
return 0;
}

In the above example, there are two add() function


1. int add(int a, int b) this function takes two integer arguments and returns a integer value
2. float add(float a, float b) this function takes two float arguments and returns a float value

Runtime polymorphism

● This type of polymorphism is achieved by Function Overriding.


● Function overriding on the other hand occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to be
overridden.

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

2. Explain the file modes and its uses in C++

mode value Effect of the mode

ios::in open for reading

ios::out open for writing

ios::ate seek (go) to the end of file at opening time

ios::app append mode: all write occur at end of file

ios::trunc truncate the file if it already exists


ios::nocreate open fails if file does not exist

ios::noreplace open fails if file already exists

ios::binary open as a binary file

● 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 Representation in Memory


There are six elements in the stack with element 16 being at the top of the stack.

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

The push operation involves the following subtasks:


1. Receiving the element to be inserted
2. Incrementing the stack pointer ( top )
3. Storing the received element at top location
Algorithm push(element)
Step 1: Start
Step 2: If top = MAX-1 goto Step 3 else goto Step 4
Step 3: Display message ”Stack Full” and exit
Step 4: top = top + 1
Step 5: stack[top] = element
Step 6: Stop

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

2. Explain the operations on Queue.

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.

Logical Representation of Queue


QUEUE OPERATIONS

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

3. Describe the infix to postfix conversion Technique

Polish Notation and Expression Conversion


The Polish Mathematician Han Lukasiewicz suggested a notation called Polish notation, which
gives two alternatives to represent an arithmetic expression, namely the postfix and prefix
notations. The fundamental property of Polish notation is that the order in which the operations
are to be performed is determined by the positions of the operators and operands in the
expression.
Hence, the advantage is that parentheses are not required while writing expressions in Polish
notation. The conventional way of writing the expression is called infix, because the binary
operators occur between the operands, and unary operators precede their operand. For example,
the expression
((A + B) \ C)/D
is an infix expression.
In postfix notation, the operator is written after its operands and in prefix notation, the operator
precedes its operands.

INFIX

OPERAND OPERATOR OPERAND

Example:

a+b

POSTFIX

OPERAND OPERAND OPERATOR

Example

ab+

PREFIX

OPERATOR OPERAND OPERAND

+ab

Infix to Postfix Expression Conversion


4. Explain polynomial addition with suitable examples

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

Coefficient Exponential Link

the term 5x2 is represented as

5 2 Link

For example, the given two polynomials are

5x2 + 4x + 2 and
5x + 5

The result of the polynomial addition is

5x2 + 9x + 7
Unit V

1. Explain Tree Traversal

BINARY TREE TRAVERSAL


Traversal is the process of visiting the various elements of a data structure. Binary tree traversal
can be performed using three methods:

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).

Preorder traversal sequence


A–B–D–E–G–C–F

Inorder traversal sequence


D–B–G–E–A–C–F

Postorder traversal sequence


D-G-E-B-F-C-A
2. Explain BFS and DFS

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)

Breadth First Search


The BFS method begins with analyzing the starting node and then progresses by analysing its
adjacent or neighbouring nodes. Once all the neighbouring nodes of the starting node are
analyzed, the algorithm starts analyzing the neighboring nodes of each of the analyzed
neighboring nodes. This method of graph traversal requires frequent backtracking to the already
analyzed nodes. As a result, a data structure is required for storing information related to the
neighboring nodes. The BFS method uses the queue data structure for storing the nodes data.

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

Depth First Search


The DFS method visits the graph nodes along the different paths. It begins analyzing the nodes
from the start to the end node and then proceeds along the next path from the start node. This
process is repeated until all the graph nodes are visited.
The DFS method also requires frequent backtracking to the already analyzed nodes. It uses the
stack data structure for storing information related to the previous nodes.
The DFS traversal sequence for the graph will be: v 1 , v2 , v4 , v8 , v5 , v7 , v3 , v6.

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

3. Explain the Dijkstra’s algorithm for finding the shortest path

Dijkstra Algorithm is a very famous greedy algorithm.


● It is used for solving the single source shortest path problem.
● It computes the shortest path from one particular source node to all other remaining nodes
of the graph.
● Shortest path problem is a problem of finding the shortest path(s) between vertices of a
given graph.
● Shortest path between two vertices is a path that has the least cost as compared to all
other existing paths.
Shortest path algorithms are a family of algorithms used for solving the shortest path problem.

Applications
● Google Maps
● Road Networks
● Logistics Research
It is important to note the following points regarding Dijkstra Algorithm-

● Dijkstra algorithm works only for connected graphs.


● Dijkstra algorithm works only for those graphs that do not contain any negative weight
edge.
● The actual Dijkstra algorithm does not output the shortest paths.
● It only provides the value or cost of the shortest paths.
● By making minor modifications in the actual algorithm, the shortest paths can be easily
obtained.
● Dijkstra algorithm works for directed as well as undirected graphs.

Algorithm:

dist[S] ← 0 // The distance to source vertex is set to 0


Π[S] ← NIL // The predecessor of source vertex is set as NIL
for all v ∈ V - {S} // For all other vertices
do dist[v] ← ∞ // All other distances are set to ∞
Π[v] ← NIL // The predecessor of all other vertices is set as NIL
S←∅ // The set of vertices that have been visited 'S' is initially empty
Q←V // The queue 'Q' initially contains all the vertices
while Q ≠ ∅ // While loop executes till the queue is not empty
do u ← mindistance (Q, dist) // A vertex from Q with the least distance is selected
S ← S ∪ {u} // Vertex 'u' is added to 'S' list of vertices that have been visited
for all v ∈ neighbors[u] // For all the neighboring vertices of vertex 'u'
do if dist[v] > dist[u] + w(u,v) // if any new shortest path is discovered
then dist[v] ← dist[u] + w(u,v) // The new value of the shortest path is selected
return dist

You might also like