0% found this document useful (0 votes)
11 views25 pages

C++ 5M

The document discusses the benefits and disadvantages of Object-Oriented Programming (OOP), including aspects like encapsulation, inheritance, and code reusability. It also covers type conversions in programming, parameter passing methods in C++, inline functions, function overloading, member function definitions, static members, friend functions, and virtual functions. Additionally, it touches on manipulators in C++ and file pointers for efficient file management.

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)
11 views25 pages

C++ 5M

The document discusses the benefits and disadvantages of Object-Oriented Programming (OOP), including aspects like encapsulation, inheritance, and code reusability. It also covers type conversions in programming, parameter passing methods in C++, inline functions, function overloading, member function definitions, static members, friend functions, and virtual functions. Additionally, it touches on manipulators in C++ and file pointers for efficient file management.

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/ 25

Unit I

1. Define the benefits of OOP.


● Modeling the real - world problem as close as possible to the user’s perspective
● Interacting easily with computational environment using familiar metaphors
● Constructing reusable software components and easily extendable libraries
● Easily modifying and extending implementations of components without having to
recode everything from scratch
● Encapsulation and data abstraction increase reliability
● Inheritance gives reusability
● Many object oriented languages provides standard class libraries which decreases the
work of programmers
● Objects can be created for real world objects
● Increases production and maintenance of software
● High degree of code sharing
● Build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of
development time and higher productivity
● The new technology promises greater programmer productivity, better quality of software
and lesser maintenance cost.
● OOP systems can be easily upgraded from small to large systems.
● It is possible that multiple instances of objects co-exist without any interference
● It is very easy to partition the work in a project based on objects.
● It is possible to map the objects in the problem domain to those in the program.
● The principle of data hiding helps the programmer to build secure programs which cannot
be invaded by the code in other parts of the program.
● By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
● Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
● The data-centered design approach enables us to capture more details of the model in an
implementable form.
● While it is possible to incorporate all these features in an OOP, their importance depends
upon the type of project and preference of the programmer.

Disadvantage of OOP
● Increases runtime for dynamic binding mechanism
● Compiler overhead
● Runtime overhead
● Re-orientation of software developer to object oriented thinking
● Benefits only in long run while managing large software projects
● The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more time
to be executed that leads to slower execution of the programme.
● OOP can not apply everywhere as it is not a universal language. It is applied only when it
is required. It is not suitable for all types of problems.
● Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
● OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
● Everything is treated as an object in OOP so before applying it we need to have excellent
thinking in terms of objects.

2. Elaborate on type conversions.


The type conversion is classified into
● Implicit Conversion
● Explicit Conversion
Implicit Conversion
The compiler performs type conversion of data items when an expression consists of data
items of different types.
It is called as implicit or automatic conversion

Operand 1 Operand 2 Result

char int int

int long long

int float float

int double double

int unsigned unsigned

long double double

double float double

Promotion:
The variable of a smaller size or lower precision data type is converted to large size or higher
precision data type is called promotion

Demotion:
The variable of a large size or higher precision data type is converted to smaller size or lower
precision data type is called demotion

Explicit Conversion:
The type conversion is performed by the programmer explicitly in the mixed mode arithmetic
operation
Type casting is used to convert a value of particular type into desired type
C language type conversion
(type) expression
(type) variable

C++ language Conversion


type( expression )
type( variable )

int x = 10, y = 3;
float z = (float) x / (float) y; // C type conversion
float f = float(x) / float(y); // C++ type conversion

3. How do you pass parameters using functions in C++? Explain with a suitable
example.

Parameter passing is a mechanism communication of data between the calling function and
called function
C++ supports three types of parameter passing
● pass by value
● pass by address
● pass by reference ( only in C++ )
Parameters are classified as
● formal parameters
● actual parameters
The formal parameters are specified in the function definition
The actual parameters are specified in the function call
1. The number of parameters in the function call and function declaration must be same
2. The data type of each parameters in the function call and in the function declaration must
be same
Pass by Value:
● The default mechanism of parameter passing is pass by value
● It does not change the value of the parameter variable in the calling function, even if the
value of the variable is changed
● The content of the actual parameters are copied to the formal parameters
● The formal parameters are stored in the the local data area of the function
● The changes made are affected only in the local data area
void swap(int x, int y)
{
int t = x;
x = y;
y = t;
}
Pass by Address:
● The address of the variable is passed as parameter
● The address of the parameter is copied
● The dereferencing operator is used to access the values
void swap(int *x, int *y)
{
int t = *x;
*x = *y;
*y = t;
}

Pass by Reference:
● Passing parameter by reference has the functionality of pass - by - address and syntax of
call by value
● Any modification made by the formal parameter is reflected in the actual parameter
● The function call is similar to that of call by value
● In the function declaration, the formal parameters are received by reference using &
operator
● The reference type formal parameters are accessed in the same way as normal variables
● Any modification to the formal parameter will affect actual parameter

void swap(int &x, int &y)


{
int t = x;
x = y;
y = x;
}

4. Briefly explain the concept of Inline Functions.


● Inline functions function is inserted in place of the function call statement during the
compilation process
● Function calls involve branching to a specified address and returning to the instruction
following the function call
● This overhead is relatively large if the time required to execute the function is less than
the context switching time
● Programs with inline functions executes fast
inline int sqr(int x)
{
return x * x;
}
int main()
{
int a = sqr(5); // a = 5 * 5;
int b = sqr(a); // b = a * a;
cout<<”b = “<<b<<”\n”
return 0:
}
The compiler have the option to treat the inline function definition as normal functions
Restrictions
The inline function with loops and branching will not be a inline function
The compiler does not allow large segment of code to be grouped as inline functions

5. What is function overloading? Write a C++ program to explain function


overloading.
● Function polymorphism or function overloading allows multiple functions to share the
same name with different parameter types
● Function polymorphism implies that the function definition can have multiple forms
Restriction
C++ does not permit overloading function differs only with return type

void swap( char &x, char &y)


{
char z = x;
x = y;
y = z;
}

void swap( int &x, int &y)


{
int z = x;
x = y;
y = z;
}

void swap( float &x, float &y)


{
float z = x;
x = y;
y = z;
}
In the above example, three functions have the same name with different argument types. In the
function call based on the given argument the respective function is called

Unit II
1. Describe the two ways of defining member functions.

The member function can be defined


1. Inside the class specification
2. Outside the class specification

1. Inside the class specification


The member function is defined inside the class declaration
class A
{
private:
int a;
public:
void seta(int x) { a = x; } // function defined inside the class
int geta() { return 0; }
};

2. Outside the class specification


The member function is defined outside the class declaration

void A :: seta(int x) // function defined outside the class


{
a = x;
}

void A :: geta() // function defined outside the class


{
return a;
}

2. Discuss about static data and static member function


Static data member:
● In some situations, it is desirable to have one or more common data members
● Example, to maintain how many objects are created for the class
● The static members can be initialized only once when the first object is created

class class_name
{
…………….
static data_type datamember;
……………..
};

data_type class_name :: datamember = value;

Static member function:


C++ allows the definition of static member function
The static member function can access only the static members
static member function declared in the public part of a class declaration can be accessed without
specifying an object of the clas

class s
{
public:
static int cnt;
static void increment()
{
cnt++;
}
};

Rules for static data member and static member function:


● Only one copy of static data members
● Static member functions can access only static members of its class
● Static data members must be defined and initialized, otherwise a linker error will be
generated
● Static members defined as public can either be accessed through the scope resolution
operator or it can be accessed through the object of the class
class_name :: static_data objectname.stat_data

3.What do you mean by Friend Function? Explain with an example.


● The private members are not accessible outside the class
● Sometimes, a function may need to access the objects of different classes
● In that situation, C++ provides the facility called friend function and friend class
● It permits a function or all the functions of another class to access a different class’s
private members
● The function that are declared with the keyword friend are called friend function
● A function can be friend to multiple multiple classes

class A
{
public:
friend void decrement(A &); // friend function
};

Characteristics of friend function


● The scope of a friend function is not limited to the class in which it has been declared as
a friend
● A friend function cannot be called using the object of that class
● The friend function is not in the scope of the class
● It is not in the scope of the class
● It can be invoked like a normal function without the use of any object
● It cannot directly access the class members directly
● It can use the object and the dot operator with each member name to access both the
private and public members

4. Write a note on Virtual Functions in C++


● Virtual function invoke the the exact version of the member function at the runtime
● Function of the base class can be overridden by the functions of the derived class
● keyword virtual is used to define virtual function
● The function virtual keyword will bound dynamically
class Father
{
string name;
public:
Father(string n) : name(n){}
virtual void print() // Virtual function
{
cout<<"Father name " << name <<"\n";
}
};

class Son : public Father


{
string name;
public:
Son(string fname, string sname) : Father(fname), name(sname){}

virtual void print() // Virtual function


{
cout<<"Son name "<< name << "\n";
}
};

Rules for Virtual Function:


● When a virtual function in a base class is created, there must be a definition for the virtual
function (Exception pure virtual function)
● They cannot be static members
● They are accessed using object pointers
● A base pointer can serve as a pointer to derived it is type compatible with derived class
● The prototype of virtual function must be same in base and derived class

Unit III
1. Write short notes on manipulators.
● Manipulating the formatting state associated with a stream
● The manipulators are functions that can be used with << or >>
● Manipulators are special functions that are specifically designed to modify the working of
a stream
● All the predefined manipulators are defined in the header file iomanip.h
● Manipulators are convenient to use than ios functions

cout << “manip1 << manip2 << element;


cout<<manip1 << element1 << element2 << manip2 << element3;
Manipulators are categorized into the following two types:
a. Non - Parameterized Manipulators
b. Parameterized Manipulators

setw(int width)
Sets the width of the output field specified by the integer parameter width
The output field width is reset to 0 every time an output is performed using the << operator

setprecision(int prec):
Sets the precision used for floating point output
The number of digits to be shown after the decimal point is given by prec

setfill(int fchar):
Sets the fill character to that specified in fchar
The fill character is used to fill (or pad) the empty space in the output field

setiosflags(long flags):
The flag can be any of the flags listed in ios stream
More than one flag can be set with the same manipulator by ORing the flags

Flag Value Bit field Effect produced

ios::left Left - justified output


ios::right Right - justified output
ios::adjustfield
ios::internal Padding occurs between the sign or base indicator and the
number, when the number output fails to fill the full width
of the field

ios::dec Decimal Conversion


ios::oct ios::basefield Octal Conversion
ios::hex Hexadecimal Conversion

ios::scientific Use exponential floating notation


ios::floatfield
ios::fixed Use ordinary floating notation

int x = 100;
cout<< hex << x << ' ' << dec << x << endl;
float f = 122.3434;
cout<< f << endl;
cout << setprecision( 5 );
cout<< f << endl;
cout<< setw( 6 ) << setfill( '0' );
cout<< setiosflags( ios::internal | ios::showbase );
cout<< hex << x << endl;
cout<< setiosflags( ios::scientific) << f << endl;
Output:
64 100
122.343
122.34
0x0064
1.22343e+02

2. Explain about file pointers and their manipulation.


● The knowledge of the logical location at which the current read or write operations to
achieve faster access to information stored in a file
● The file management system associates two parties with each file, called file pointers
● The are called get pointer (input pointer) and put pointer (output pointer)
● These pointers facilitate the movement across the file while reading or writing
● The get pointer specifies a location from where the current reading operation is initiated
● The put pointer specifies a location from where the current writing operation is initiated
● On completion of a read or write operation, the pointer will be advanced automatically
Default Actions:
The file pointers are set to a suitable location initially based on the mode in which the file is
opened
Read Only Mode
The input pointer (get pointer) is initialized to point to the beginning of the file

H e l l o W o r l d

get pointer points to H to read

Write only Mode:


The existing contents of the file are deleted( if a given file already exists ) and the output pointer
is set to point to the beginning of the file

Output pointer points to the first index

Append Mode:
The existing contents of the file remain unaffected( if already exists ) and the output pointer is set
to point to the end of the file

H e l l o W o r l d
The output pointer points next to the letter d

The C++ I/O system supports four functions for setting a file pointer to desired position inside
the file or to get the current file pointer

Function Member of the Class Action Performed

seekg() ifstream Moves get file pointer to a specific location

seekp() ofstream Moves put file pointer to a specific location

tellg() ifstream Returns the current position of the get pointer

tellp() ofstream Returns the current position of the put pointer

3. Discuss about Error Handling during File Operations in C++.


The following are the different situations that can arise while manipulating a file:
1. Attempting to open a non - existence file in read mode
2. Trying to open a read - only marked file in write mode
3. Trying to open a file with invalid name
4. Attempting to read beyond the end of the file
5. Sufficient disk space is not available while writing to a file
6. Attempting to manipulate an unopened file
7. Media(disk) errors reading/writing a file

Function Meaning of Return Value

eof() TRUE(non zero), if EOF encountered while reading,


otherwise FALSE(zero)

fail() TRUE, if read or write operation has failed; otherwise FALSE

bad() TRUE, invalid operation is attempted or any unrecoverable errors


FALSE otherwise it can be recovered

good() TRUE, if operation is successful; otherwise FALSE

clear() clear error states and further operations can be attempted

4. What are Command-Line Arguments? Briefly explain.


Command line argument is a parameter supplied to the program when it is invoked. It is mostly
used when the program is controlled from outside. Command line arguments are passed to the
main() method

int main(int argc, char *argv[])

argc counts the number of arguments on the command line and


argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed
to the program.

int main(int argc, char *argv[])


{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
argv[0] holds the name of the program and
argv[1] points to the first command line argument and
argv[n] gives the last argument.
If no argument is supplied, argc will be 1.

5. Explain primitive and composite data types.


Data structures are primarily divided into two classes:
1. primitive and
2. non-primitive.

Data Structures

Primitive Data Types Non Primitive Data Types

Linear Non Linear


Int, float, char arrays, stacks, queues, linked
trees and graphs
lists
Primitive data structures
● It include all the fundamental data structures that can be directly manipulated by
machine-level instructions.
● Some of the common primitive data structures include integer, character, real, boolean,
etc.

Non-primitive data structures


● It refers to all those data structures that are derived from one or more primitive data
structures
● The objective of creating non-primitive data structures is to form sets of homogeneous or
heterogeneous data elements.
Non-primitive data structures are categorized into two types:
1. linear and
2. non-linear

Linear data structures


All the data elements are arranged in a linear or sequential fashion.
Examples:
1. arrays,
2. stacks,
3. queues,
4. linked lists, etc

Non-linear data structures


In Non Linear data structures there is no definite order or sequence in which data elements are
arranged
For instance, a non-linear data structure could arrange data elements in a hierarchical fashion.
Examples:
1. trees and
2. graphs.

6. Briefly explain about an asymptotic notation.


Asymptotic notation is the most simple and easiest way of describing the running time of an
algorithm
It represents the efficiency and performance of an algorithm in a systematic and meaningful
manner
Asymptotic notations describe time complexity in terms of three common measures,
1. Best case (or ‘fastest possible’),
2. Worst case (or ‘slowest possible’), and
3. Average case (or ‘average time’).

Big-Oh Notation
The big-oh notation is a method that is used to express the upper bound of the running time of an
algorithm
It is denoted by ‘O’
we can compute the maximum possible amount of time that an algorithm will take for its
completion

Definition
Consider f (n) and g(n) to be two positive functions of n, where n is the size of the input data.
Then, f (n) is big-oh of g(n), if and only if there exists a positive constant C and an integer n0 ,
such that f (n) ≤ Cg(n) and n > n0 Here, f (n) = O(g(n))

Omega Notation
The omega notation is a method that is used to express the lower bound of the running time of an
algorithm
Omega notation is denoted by ‘Ω’
Using this notation, you can compute the minimum amount of time that an algorithm will take
for its completion
Definition
Consider f(n) and g(n) to be two positive functions of n, where n is the size of the input data.
Then, f(n) is omega of g(n), if and only if there exists a positive constant C and an integer n0 ,
such that f(n) ≥ Cg(n) and n > n0. Here, f(n) = Ω(g(n))

Theta Notation
The theta notation is a method that is used to express the running time of an algorithm between
the lower and upper bounds.
Theta notation is denoted by ‘θ’.
Using this notation, we can compute the average time that an algorithm will take for its
completion.
Definition
Consider f(n) and g(n) to be two positive functions of n, where n is the size of the input data.
Then, f(n) is theta of g(n), if and only if there exists two positive constants C 1 and C 2 , such
that, C1 g(n) ≤ f(n) ≤ C2 g(n). Here, f(n) = θ(g(n)).

Unit IV
1. What is a Circular Queue? Explain.
● A circular queue is a queue whose start and end locations are logically connected with
each other.
● The start location comes after the end location.
● Circular queues remove one of the main disadvantages of array implemented queues in
which a lot of memory space is wasted due to inefficient utilization.
● if the queue is filled till its capacity, i.e., the end location, then the start location will be
checked for space, and if it is empty, the new element will be added there.

Insertion
Algorithm insert(element)
Step 1: Start
Step 2: if (front = 0 and rear = MAX-1) OR front = rear+1 goto Step 3 else goto Step 4
Step 3: Display message, “Queue is Full” and goto Step 10
Step 4: if front = NULL goto Step 5 else goto Step 6
Step 5: Set front = rear = 0
Step 6: if rear = MAX-1 goto Step 7 else goto Step 8
Step 7: Set rear = 0
Step 8: Set rear = rear + 1
Step 9: Set queue[rear] = element
Step 10: Stop

Delete:
Algorithm delete()
Step 1: Start
Step 2: if front = NULL goto Step 3 else goto Step 4
Step 3: Display message, “Queue is Empty” and goto Step 13
Step 4: Set i = queue[front]
Step 5: if front = rear goto Step 6 else goto Step 8
Step 6: Set front = rear = NULL
Step 7: Return the deleted element i and go to Step 13
Step 8: if front = MAX-1 goto Step 9 else goto Step 11
Step 9: Set front = 0
Step 10: Return the deleted element i and go to Step 13
Step 11: Set front = front + 1
Step 12: Return the deleted element i
Step 13: Stop
2. Write about operations of singly linked list.
The implementation of a linked list involves two tasks:
1. Declaring the list node
2. Defining the linked list operations

struct node
{
int INFO;
struct node *NEXT;
};
typedef struct node NODE;

The structure declaration defines a new data type called NODE


● It represents a linked list node.
● The node structure contains two members,
● INFO for storing data and
● NEXT for storing the address of the next node.
● structures that contain pointer references to their own types are called self referential
structures.

The Operations performed on linked list are:


1. Insert
2. Delete
3. Search
4. Print

The insert operation adds a new element to the linked list


The following tasks are performed while adding the new element
1. Memory space is reserved for the new node.
2. The element is stored in the INFO part of the new node.
3. The new node is connected to the existing nodes in the list
Inserting position
1. Inserting the new element at the beginning of the list
2. Inserting the new element at the end of the list
3. Inserting the new element somewhere at the middle of the list
Algorithm Insert(value)
Step 1: Start
Step 2: Allocate a new node and assign its address to the pointer
Step 3: Store the element value to be inserted in the INFO part of the new node
Step 4: if FIRST = NULL, then goto Step 5 else goto step 7
Step 5: Update the FIRST and LAST pointers
Step 6: Set PTR->NEXT = NULL and goto Step 8
Step 7: Set LAST->NEXT = PRT, PRT-> = NULL and LAST = PTR
Step 8: Stop

Deletion:
The delete operation removes an existing element from the linked list. The following tasks are
performed while deleting an existing element:
1. The location of the element is identified.
2. The element value is retrieved. In some cases, the element value is simply ignored.
3. The link pointer of the preceding node is reset
Depending on the location from where the element is to be deleted, there are three scenarios
possible, which are:
1. Deleting an element from the beginning of the list.
2. Deleting an element from the end of the list.
3. Deleting an element somewhere from the middle of the list.
Algorithm delete(value)
Step 1: Start
Step 2: Call the search module to search the location of the node to deleted and assign it to LOC
pointer
Step 3: If LOC=NULL goto Step 4 else goto Step 5
Step 4: Return “Delete operation unsuccessful: Element not present” and Stop
Step 5: If LOC=FIRST goto Step 6 else goto Step 10
Step 6: If FIRST=LAST goto Step 7 else goto Step 8
Step 7: Set FIRST=LAST=NULL and goto Step 9
Step 8: Set FIRST=FIRST->NEXT
Step 9: Return (“Delete operation successful”) and Stop
Step 10: Set TEMP=LOC-1
Step 11: Set TEMP->NEXT=LOC->NEXT
Step 12: If LOC=LAST goto Step 13 else goto Step 14
Step 13: Set LAST=TEMP
Step 14: Return “Delete operation successful”
Step 15: Stop

Searching:
The search operation helps to find an element in the linked list. The following tasks are
performed while searching an element:
1. Traverse the list sequentially starting from the first node.
2. Return the location of the searched node as soon as a match is found.
3. Return a search failure notification if the entire list is traversed without any match.
The NEXT pointers help in traversing the linked list from start till end.

Algorithm Search (value)


Step 1: Start
Step 2: If FIRST=NULL goto Step 3 else goto Step 4
Step 3: Return “Search unsuccessful: Element not present” and Stop
Step 4: Set PTR=FIRST
Step 5: Repeat Steps 6-8 until PTR!=LAST
Step 6: If PTR->INFO=value goto Step 7 else goto Step 8
Step 7: Return PTR and Stop
Step 8: Set PTR=PTR->NEXT
Step 9: If LAST->INFO=value goto Step 10 else goto Step 11
Step 10: Return (“Search successful”, LAST) and Stop
Step 11: Return (“Search unsuccessful: Element not present”)
Step 12: Stop

Print:
The print operation prints or displays the linked list elements on the screen.
To print the elements, the linked list is traversed from start till end using NEXT pointers
Algorithm print ()
Step 1: Start
Step 2: If FIRST=NULL goto Step 3 else goto Step 4
Step 3: Display (“Empty List”) and Stop
Step 4: If FIRST=LAST goto Step 5 else goto Step 6
Step 5: Display (FIRST->INFO) and Stop
Step 6: Set PTR=FIRST
Step 7: Repeat Steps 8-9 until PTR!=LAST
Step 8: Display (PTR->INFO)
Step 9: Set PTR=PTR->NEXT
Step 10: Display (LAST->INFO)
Step 11: Stop

3. Discuss about Doubly Linked List.

The implementation of a doubly linked list involves two tasks:


● Declaring the list node
● Defining the list operations

Doubly Linked List Node Declaration


struct node
{
int INFO;
struct node *NEXT;
struct node *PREVIOUS;
};
typedef struct node NODE;

a new data type called NODE that represents a doubly linked list node.
The node structure contains three members
1. INFO for storing integer data values,
2. NEXT for storing address of the next node, and
3. PREVIOUS for storing the address of the previous node.

Insert:
The new node pointer’s PREVIOUS and NEXT is also required to be updated for the new node
at the time of insertion.

Algorithm insert (value)


Step 1: Start
Step 2: Set PTR = addressof (New Node)
Step 3: Set PTR->INFO = value;
Step 4: If FIRST = NULL, then goto Step 5 else goto Step 7
Step 5: Set FIRST=PTR and LAST=PTR
Step 6: Set PTR->NEXT = PTR -> PREVIOUS = NULL and goto Step 8
Step 7: Set LAST->NEXT=PTR, PTR->PREVIOUS = LAST, PTR->NEXT=NULL, and
LAST=PTR
Step 8: Stop

Delete:
The Selected node’s pointer PREVIOUS and NEXT of the adjacent node is required to be
updated at the time of deletion.

Algorithm delete (value)


Step 1: Start
Step 2: Set LOC = search (value)
Step 3: If LOC=NULL goto Step 4 else goto Step 5
Step 4: Return “Delete operation unsuccessful: Element not present” and Stop
Step 5: If LOC=FIRST goto Step 6 else goto Step 10
Step 6: If FIRST=LAST goto Step 7 else goto Step 8
Step 7: Set FIRST=LAST=NULL and goto Step 9
Step 8: Set FIRST->NEXT->PREVIOUS=NULL and FIRST=FIRST->NEXT
Step 9: Return (“Delete operation successful”) and Stop
Step 10: Set TEMP=LOC-1
Step 11: If LOC=LAST goto Step 12 else goto Step 13
Step 12: Set LAST=TEMP, TEMP->NEXT=NULL and goto Step 15
Step 13: Set TEMP->NEXT=LOC->NEXT
Step 14: Set LOC->NEXT->PREVIOUS=TEMP
Step 15: Return “Delete operation successful”
Step 16: Stop
Unit V
1. Briefly explain about the conversion technique of Forest to Binary Tree.
A forest can also be transferred into a binary tree.
Firstly all trees are transferred into binary trees.
Then all binary trees are transferred into a corresponding binary tree: from the first binary
tree, the next tree’s root is as the right child of the previous tree’s root.

Also, define root(T1), ..., root(Tm) to be the children of root(T), with root(Ti) being the i-th
child. The nodes root(T1), ..., root(Tm) are siblings.
It is often more convenient to represent an ordered tree as a rooted binary tree, so that each
node can be stored in the same amount of memory. The conversion is performed by the
following steps:
1. remove all edges from each node to its children;
2. for each node, add an edge to its first child in T (if any) as the left child;
3. for each node, add an edge to its next sibling in T (if any) as the right child

In most cases, the height of the tree (the number of edges in the longest root-to-leaf path)
increases after the conversion. This is undesirable because the complexity of many algorithms on
trees depends on its height.

2. Describe the representation of a binary tree.


A data structure is said to be non linear if its elements form a hierarchical classification where
data items appear at various levels. Trees and Graphs are widely used non-linear data structures.
Tree and graph structures represent hierarchical relationship between individual data elements.
Graphs are nothing but trees with certain restrictions removed.
Trees represent a special case of more general structures known as graphs. In a graph, there is no
restrictions on the number of links that can enter or leave a node, and cycles may be present in
the graph.

Tree is a non-linear data structure which organizes data in hierarchical structure and this is a
recursive definition.
A tree data structure can also be defined as follows...
A tree is a finite set of one or more nodes such that:
There is a specially designated node called the root. The remaining nodes are partitioned into
n>=0 disjoint sets T1, ..., Tn, where each of these sets is a tree. We call T1, ..., Tn are the
subtrees of the root.

Tree Representations
A tree data structure can be represented in two methods. Those methods are as follows...
1.List Representation
2. Left Child - Right Sibling Representation
Consider the following tree...

1. List Representation
In this representation, we use two types of nodes one for representing the node with data and
another for representing only references. We start with a node with data from root node in the
tree. Then it is linked to an internal node through a reference node and is linked to any other
node directly. This process repeats for all the nodes in the tree.
The above tree example can be represented using List representation as follows...
2. Left Child - Right Sibling Representation
In this representation, we use list with one type of node which consists of three fields namely
Data field, Left child reference field and Right sibling reference field. Data field stores the actual
value of a node, left reference field stores the address of the left child and right reference field
stores the address of the right sibling node. Graphical representation of that node is as follows...

In this representation, every node's data field stores the actual value of that node. If that node has
left child, then left reference field stores the address of that left child node otherwise that field
stores NULL. If that node has right sibling then right reference field stores the address of right
sibling node otherwise that field stores NULL.

3. Write a note on Hashing Tables.

Hashing is a common method of accessing data records using the hash table. Hashing can be
used to build, search, or delete from a table.

Hash Table:
A hash table is a data structure that stores records in an array, called a hash table. A Hash table
can be used for quick insertion and searching.
Hash Function:
● It is a method for computing table index from key.
● A good hash function is simple, so it can be computed quickly
● The major advantage of hash tables is their speed.
● If the hash function is slow, this speed will be degraded.
● The purpose of a hash function is to take a range of key values and transform them into
index values in such a way that the key values are distributed randomly across all the
indices of the hash table.
There are many hash functions approaches as follows:

1. Division Method
2. Mid Square Method
3. Folding Method
4. Radix Hashing

1. Division Method:
Mapping a key K into one of m slots by taking the remainder of K divided by m.
h(K) = K mod m

2. Mid - Square Method:


Mapping a key K into one of m slots, by getting the some middle digits from value K2

3. Folding Method:
Divide the key K into some sections, besides the last section having the same length.
Then, add these sections together.

4. Radix Hashing:
Transform the number into another base and then divide by the maximum address

You might also like