advanced c c++

155
Advanced C Programming Introduction to Data Structures Data Structures: A data structure is an arrangement of data in a computer's memory or even disk storage. Data structures can be classified into two types Linear Data Structures Non Linear Data Structures Linear Data Structures: Linear data structures are those data structures in which data elements are accessed (read and written) in sequential fashion ( one by one) Eg: Stacks , Queues, Lists, Arrays Non Linear Data Structures: Non Linear Data Structures are those in which data elements are not accessed in sequential fashion. Eg: trees, graphs Algorithm: Step by Step process of representing solution to a problem in words is called an Algorithm. Characteristics of an Algorithm: 1

Upload: muilevan

Post on 06-May-2015

378 views

Category:

Technology


2 download

DESCRIPTION

First upload

TRANSCRIPT

Page 1: Advanced c c++

Advanced C Programming

Introduction to Data Structures

Data Structures:A data structure is an arrangement of data in a computer's memory or even disk storage.

Data structures can be classified into two types

Linear Data Structures

Non Linear Data Structures

Linear Data Structures:

Linear data structures are those data structures in which data elements are accessed (read and

written) in sequential fashion ( one by one)

Eg: Stacks , Queues, Lists, Arrays

Non Linear Data Structures:

Non Linear Data Structures are those in which data elements are not accessed in sequential

fashion.

Eg: trees, graphs

Algorithm:

Step by Step process of representing solution to a problem in words is called an Algorithm.

Characteristics of an Algorithm:

Input : An algorithm should have zero or more inputs

Output: An algorithm should have one or more outputs

Finiteness: Every step in an algorithm should end in finite amount of time

Unambiguous: Each step in an algorithm should clearly stated

Effectiveness: Each step in an algorithm should be effective

1

Page 2: Advanced c c++

Advanced C Programming

Characteristics of Data Structures

Data Structure Advantages Disadvantages

Array Quick insertsFast access if index known

Slow searchSlow deletesFixed size

Ordered Array Faster search than unsorted array Slow insertsSlow deletesFixed size

Stack Last-in, first-out acces Slow access to other items

Queue First-in, first-out access Slow access to other items

Linked List Quick insertsQuick deletes

Slow search

Binary Tree Quick searchQuick insertsQuick deletes(If the tree remains balanced)

Deletion algorithm is complex

Red-Black Tree Quick searchQuick insertsQuick deletes(Tree always remains balanced)

Complex to implement

2-3-4 Tree Quick searchQuick insertsQuick deletes(Tree always remains balanced)(Similar trees good for disk storage)

Complex to implement

Hash Table Very fast access if key is knownQuick inserts

Slow deletesAccess slow if key is not knownInefficient memory usage

Heap Quick insertsQuick deletesAccess to largest item

Slow access to other items

Graph Best models real-world situations Some algorithms are slow and very complex

2

Page 3: Advanced c c++

Advanced C Programming

Stack :

Stack is a Linear Data Structure which follows Last in First Out mechanism.

It means: the first element inserted is the last one to be removed

Stack uses a variable called top which points topmost element in the stack. top is incremented

while pushing (inserting) an element in to the stack and decremented while poping (deleting) an

element from the stack

Push(A) Push(B) Push(C) Push(D) Pop()

Valid Operations on Stack:

Inserting an element in to the stack (Push)

Deleting an element in to the stack (Pop)

Displaying the elements in the queue (Display)

Note:

While pushing an element into the stack, stack is full condition should be checked

While deleting an element from the stack, stack is empty condition should be checked

Applications of Stack:

Stacks are used in recursion programs

Stacks are used in function calls

Stacks are used in interrupt implementation

ABA

CBA

CBA

top

top top

topDCBA

3

top

Page 4: Advanced c c++

Advanced C Programming

Queue:

Queue is a Linear Data Structure which follows First in First out mechanism.

It means: the first element inserted is the first one to be removed

Queue uses two variables rear and front. Rear is incremented while inserting an element into the

queue and front is incremented while deleting element from the queue

Insert(A) Insert(B) Insert(C) Insert(D) Delete()

Valid Operations on Queue:

Inserting an element in to the queue

Deleting an element in to the queue

Displaying the elements in the queue

Note:While inserting an element into the queue, queue is full condition should be checked

While deleting an element from the queue, queue is empty condition should be checked

Applications of Queues:

Real life examples

Waiting in line

Waiting on hold for tech support

Applications related to Computer Science

Threads

Job scheduling (e.g. Round-Robin algorithm for CPU allocation)

ABA

CBA

DCBA

DCB

rearfront

rearfront

rear

front

rear

front

4

rear

front

Page 5: Advanced c c++

Advanced C Programming

Linked List:

To overcome the disadvantage of fixed size arrays linked list were introduced.

A linked list consists of nodes of data which are connected with each other. Every node consist

of two parts data and the link to other nodes. The nodes are created dynamically.

NODE

Data link

Types of Linked Lists:

Single linked list

Double linked list

Circular linked list

Valid operations on linked list:

Inserting an element at first position

Deleting an element at first position

Inserting an element at end

Deleting an element at end

Inserting an element after given element

Inserting an element before given element

Deleting given element

bat

bat cat sat vat NULL

5

Page 6: Advanced c c++

Advanced C Programming

Trees :

A tree is a Non-Linear Data Structure which consists of set of nodes called vertices and set of edges which links vertices

Terminology:

Root Node: The starting node of a tree is called Root node of that tree

Terminal Nodes: The node which has no children is said to be terminal node or leaf .

Non-Terminal Node: The nodes which have children is said to be Non-Terminal Nodes

Degree: The degree of a node is number of sub trees of that node

Depth: The length of largest path from root to terminals is said to be depth or height of

the tree

Siblings: The children of same parent are said to be siblings

Ancestors: The ancestors of a node are all the nodes along the path from the root to the

node

A

B C

D

G

E F

IH

Property ValueNumber of nodes : 9Height : 4Root Node : ALeaves : ED, H, I, F, CInterior nodes : D, E, GNumber of levels : 5Ancestors of H : IDescendants of B : D,E, FSiblings of E : D, F

6

Page 7: Advanced c c++

Advanced C Programming

Binary Trees:

Binary trees are special class of trees in which max degree for each node is 2

Recursive definition:

A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint

binary trees called the left subtree and the right subtree.

Any tree can be transformed into binary tree. By left child-right sibling representation.

Binary Tree Traversal Techniques:

There are three binary tree traversing techniques Inorder

Preorder Postorder

Inorder: In inorder traversing first left subtree is visited followed by root and right subtree

Preorder: In preorder traversing first root is visited followed by left subtree and right subtree.

Postorder: In post order traversing first left tree is visited followed by right subtree and root.

A

B

C

D

E

F G K

7

Page 8: Advanced c c++

Advanced C Programming

Binary Search Tree:

A Binary Search Tree (BST) is a binary tree which follows the following conditons

Every element has a unique key.

The keys in a nonempty left subtree are smaller than the key in the root of subtree.

The keys in a nonempty right subtree are grater than the key in the root of subtree.

The left and right subtrees are also binary search trees.

Valid Operations on Binary Search Tree:

Inserting an element

Deleting an element

Searching for an element

Traversing

63

41 89

34 5672 95

8

Page 9: Advanced c c++

Advanced C Programming

Avl Tree:

If in a binary search tree, the elements are inserted in sorted order then the height will be n,

where n is number of elements. To overcome this disadvantage balanced trees were introduced.

Balanced binary search trees

An AVL Tree is a binary search tree such that for every internal node v of T, the

heights of the children of v can differ by at most 1.

88

44

17 78

32 50

48 62

2

4

1

1

2

3

1

1

Operations of Avl tree:

Inserting an element

Deleting an element

Searching for an element

Traversing

Height balancing

9

Page 10: Advanced c c++

Advanced C Programming

Graphs

A graph is a Non-Linear Data Structure which consists of set of nodes called vertices V and set

of edges E which links vertices

Note: A tree is a graph with out loops

Graph Tree

Graph Traversal:

Problem: Search for a certain node or traverse all nodes in the graph

Depth First Search

Once a possible path is found, continue the search until the end of the path

Breadth First Search

Start several paths at a time, and advance in each one step at a time

0

1 2

3

0

1 2

3 4 5 6

10

Page 11: Advanced c c++

Advanced C Programming

Object Oriented Programming:

Introduction to Object Oriented ProgrammingYou've heard it a lot in the past several years. Everybody is saying it.

What is all the fuss about objects and object-oriented technology? Is it real? Or is it hype? Well,

the truth is--it's a little bit of both. Object-oriented technology does, in fact, provide many

benefits to software developers and their products. However, historically a lot of hype has

surrounded this technology, causing confusion in both managers and programmers alike. Many

companies fell victim to this hardship (or took advantage of it) and claimed that their software

products were object-oriented when, in fact, they weren't. These false claims confused

consumers, causing widespread misinformation and mistrust of object-oriented technology.

Object:

As the name object-oriented implies, objects are key to understanding object-oriented

technology. You can look around you now and see many examples of real-world objects: your

dog, your desk, your television set, your bicycle.

Definition: An object is a software bundle of variables and related methods

Class:

In the real world, you often have many objects of the same kind. For example, your bicycle is

just one of many bicycles in the world. Using object-oriented terminology, we say that your

11

Page 12: Advanced c c++

Advanced C Programming

bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state

(current gear, current cadence, two wheels) and behavior (change gears, brake) in common.

However, each bicycle's state is independent of and can be different from other bicycles.

Definition: A class is a blueprint or prototype that defines the variables and methods common to

all objects of a certain kind.

Inheritance:

Acquiring the properties of one class in another class is called inheritance

The Benefits of Inheritance

Subclasses provide specialized behaviors from the basis of common elements provided

by the super class. Through the use of inheritance, programmers can reuse the code in the

superclass many times.

Programmers can implement superclasses called abstract classes that define "generic"

behaviors. The abstract superclass defines and may partially implement the behavior but

much of the class is undefined and unimplemented. Other programmers fill in the details

with specialized subclasses.

Data Abstraction:

The essential element of object oriented programming in abstraction. The complexity of

programming in object oriented programming is maintained through abstraction.

For example, the program consist of data and code which work over data. While executing a

program we don’t thing in which location that data is being stored how the input device is

transferring the input to the memory etc. this abstraction allows us to execute the program

without thinking deeply about the complexity of execution of program.

Encapsulation:

Encapsulation is the mechanism that binds together code and the data and keeps them safe from

outside world. In the sense it is a protective wrapper that prevents the code and data from being

12

Page 13: Advanced c c++

Advanced C Programming

accessed by other code defied outside the wrapper. Access is controlled through a well defined

interface.

Polymorphism:

Existing in more that one form is called polymorphism.

Polymorphism means the ability to take more that one form. For example an operation may

exhibit different behavior in different behavior in different instances.

For example consider operation of addition. For two numbers the operation will generate a sum.

If the operands are string the operation would produces a third string by concatenation.

C++ supports polymorphism through method overloading and operator overloading

Method overloading:

if the same method name used for different procedures that the method is said to be overloaded.

Dynamic Binding:

Binding refer to the linking of a procedure call to the code to be executed in response to the call.

Dynamic binding means that the code associated with a given procedure call is not know until

the time of the call at runtime. It is associated with a polymorphism reference depends on the

dynamic type of that reference.

Message communication:

An object oriented program consists of objects that communicate with each other. The process

of programming in an object oriented language therefore involves the following basic steps:

1. creating classes that define objects and their behaviors.

2. creating objects from class definitions.

3. establishing communication among objects.

13

Page 14: Advanced c c++

Advanced C Programming

Abstract Data Types:

An Abstract Data Type (ADT) is more a way of looking at a data structure: focusing on what it

does and ignoring how it does its job. A stack or a queue is an example of an ADT. It is

important to understand that both stacks and queues can be implemented using an array. It is also

possible to implement stacks and queues using a linked list. This demonstrates the "abstract"

nature of stacks and queues: how they can be considered separately from their implementation.

To best describe the term Abstract Data Type, it is best to break the term down into "data type"

and then "abstract".

Data type:

When we consider a primitive type we are actually referring to two things: a data item with

certain characteristics and the permissible operations on that data. An int in Java, for example,

can contain any whole-number value from -2,147,483,648 to +2,147,483,647. It can also be used

with the operators +, -, *, and /. The data type's permissible operations are an inseparable part of

its identity; understanding the type means understanding what operations can be performed on it.

In C++, any class represents a data type, in the sense that a class is made up of data (fields) and

permissible operations on that data (methods). By extension, when a data storage structure like a

stack or queue is represented by a class, it too can be referred to as a data type. A stack is

different in many ways from an int, but they are both defined as a certain arrangement of data

and a set of operations on that data.

abstract

Now lets look at the "abstract" portion of the phrase. The word abstract in our context stands for

"considered apart from the detailed specifications or implementation".

In C++, an Abstract Data Type is a class considered without regard to its implementation. It can

be thought of as a "description" of the data in the class and a list of operations that can be carried

out on that data and instructions on how to use these operations. What is excluded though, is the

14

Page 15: Advanced c c++

Advanced C Programming

details of how the methods carry out their tasks. An end user (or class user), you should be told

what methods to call, how to call them, and the results that should be expected, but not HOW

they work.

We can further extend the meaning of the ADT when applying it to data structures such as a

stack and queue. In Java, as with any class, it means the data and the operations that can be

performed on it. In this context, although, even the fundamentals of how the data is stored should

be invisible to the user. Users not only should not know how the methods work, they should also

not know what structures are being used to store the data.

Consider for example the stack class. The end user knows that push() and pop() (amoung other

similar methods) exist and how they work. The user doesn't and shouldn't have to know how

push() and pop() work, or whether data is stored in an array, a linked list, or some other data

structure like a tree.

15

Page 16: Advanced c c++

Advanced C Programming

Stack ADT AlgorithmsPush(item)

{

If (stack is full) print “ stack over flow”

else

Increment top ;

Stack [top]= item;

}

Pop()

{

If( stack is empty) print” stack under flow”

else

Decrement top

}

Display()

{

If ( stack is empty) print” no element to display”

else

for i= top to 0 step -1

Print satck[i];

}

16

Page 17: Advanced c c++

Advanced C Programming

Stack ADT

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

class stack{

int stk[5];int top;public:stack(){

top=-1;}

void push(int x){

if(top > 4){cout <<"stack over flow";return;}stk[++top]=x;cout <<"inserted" <<x;

}

void pop(){

if(top <0){cout <<"stack under flow";return;}cout <<"deleted" <<stk[top--];

}

void display(){

if(top<0){cout <<" stack empty";return;}

17

Page 18: Advanced c c++

Advanced C Programming

for(int i=top;i>=0;i--)cout <<stk[i] <<" ";}

};

void main(){

int ch;

stack st;clrscr();while(1){cout <<"\n1.push 2.pop 3.display 4.exit\nEnter ur choice";cin >> ch;switch(ch){case 1: cout <<"enter the element";

cin >> ch; st.push(ch);break;

case 2: st.pop(); break;case 3: st.display();break;case 4: exit(0);}}

}

OUTPUTS1.push 2.pop 3.display 4.exitEnter ur choice2stack under flow1.push 2.pop 3.display 4.exitEnter ur choice1enter the element2inserted21.push 2.pop 3.display 4.exitEnter ur choice1enter the element3inserted31.push 2.pop 3.display 4.exitEnter ur choice2deleted31.push 2.pop 3.display 4.exitEnter ur choice1enter the element5

18

Page 19: Advanced c c++

Advanced C Programming

Queue ADT Algorithms

Insert ( item)

{

If rear = max -1 then print “ queue is full”

else

{

Increment rear

Queue [rear]=item;

}

}

Delete()

{

If front = rear print “queue is empty”

else

Increment front

}

Display()

{

If front=rear print “queue is empty “

else

For i =front to rear

Print queue[i];

}

19

Page 20: Advanced c c++

Advanced C Programming

Queue ADT

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

class queue{

int queue[5];int rear,front;public:queue(){

rear=-1;front=-1;

}

void insert(int x){

if(rear > 4){cout <<"queue over flow";front=rear=-1;return;}queue[++rear]=x;cout <<"inserted" <<x;

}

void delet(){

if(front==rear){cout <<"queue under flow";return;}cout <<"deleted" <<queue[++front];

}

void display(){

if(rear==front){cout <<" queue empty";

20

Page 21: Advanced c c++

Advanced C Programming

return;}

for(int i=front+1;i<=rear;i++)cout <<queue[i]<<" ";

}};

void main(){

int ch;queue qu;clrscr();while(1){

cout <<"\n1.insert 2.delet 3.display 4.exit\nEnter ur choice";cin >> ch;switch(ch){case 1: cout <<"enter the element";

cin >> ch; qu.insert(ch);break;

case 2: qu.delet(); break;case 3: qu.display();break;case 4: exit(0);}

}}

OUTPUT1.insert 2.delet 3.display 4.exitEnter ur choice1enter the element21inserted211.insert 2.delet 3.display 4.exitEnter ur choice1enter the element22inserted221.insert 2.delet 3.display 4.exitEnter ur choice1enter the element16inserted161.insert 2.delet 3.display 4.exitEnter ur choice321 22 16 1.insert 2.delet 3.display 4.exit

21

Page 22: Advanced c c++

Advanced C Programming

Algorithm for Stack Using Linked ListPush(item)

{

If (stack is full) print “ stack over flow”

else

goto end of list and let it be temp

temp->next=item

item->next=NULL;

}

Pop()

{

If(head is null) print” stack under flow”

else

goto last but one node and let it be temp

temp->next=NULL

}

Display()

{

If ( head=NULL) print” no element to display”

else

{

Temp=head;

While(temp!=NULL)

{

Print(“temp->data)

Temp=temp->next;

}

}

22

Page 23: Advanced c c++

Advanced C Programming

Stack Using Linked List

#include<iostream.h>#include<conio.h>#include<stdlib.h>class node{

public:class node *next;int data;

};

class stack : public node{

node *head;int tos;public:stack(){

os=-1;}void push(int x){

if (tos < 0 ){

head =new node;head->next=NULL;head->data=x;tos ++;

}else{

node *temp,*temp1;temp=head;if(tos >= 4){cout <<"stack over flow";return;}tos++;while(temp->next != NULL)

temp=temp->next;temp1=new node;temp->next=temp1;

23

Page 24: Advanced c c++

Advanced C Programming

temp1->next=NULL;temp1->data=x;

}}

void display(){ node *temp; temp=head; if (tos < 0) { cout <<" stack under flow"; return; } while(temp != NULL) { cout <<temp->data<< " "; temp=temp->next; }

} void pop() {

node *temp;temp=head;if( tos < 0 ){cout <<"stack under flow";return;}tos--;while(temp->next->next!=NULL){temp=temp->next;}

temp->next=NULL; }

};void main(){

stack s1;int ch;clrscr();while(1){

cout <<"\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n enter ru choice:";

24

Page 25: Advanced c c++

Advanced C Programming

cin >> ch;switch(ch){case 1:

cout <<"\n enter a element";cin >> ch;s1.push(ch);break;

case 2: s1.pop();break;case 3: s1.display();

break;case 4: exit(0);}

}}

OUTPUT1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:1 enter a element23

1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:1 enter a element67

1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:323 671.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:2

1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:3231.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:2

1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:2stack under flow1.PUSH 2.POP 3.DISPLAY 4.EXITenter ru choice:4

25

Page 26: Advanced c c++

Advanced C Programming

Algorithm Queue using Linked List

Insert ( item){ If rear = max -1 then print “ queue is full” else {

Increment rear Create a new node called itemgoto last node in the list and let it be temptemp-next=item;item-next=NULL;

}}

Delete(){ If front = rear print “queue is empty”else{

Increment fronthead=head-next;

}}

Display(){If front=rear print “queue is empty “else Temp=head;

While(temp!=NULL){

Print(“temp-data)Temp=temp-next;

}

}

26

Page 27: Advanced c c++

Advanced C Programming

Queue using Linked List

#include<iostream.h>#include<conio.h>#include<stdlib.h>class node{public:class node *next;int data;};

class queue : public node{

node *head;int front,rare;public:queue(){front=-1;rare=-1;}void push(int x){

if (rare < 0 ){

head =new node;head->next=NULL;head->data=x;rare ++;

}else{

node *temp,*temp1;temp=head;if(rare >= 4){cout <<"queue over flow";return;}rare++;while(temp->next != NULL)

temp=temp->next;temp1=new node;

27

Page 28: Advanced c c++

Advanced C Programming

temp->next=temp1;temp1->next=NULL;temp1->data=x;

}}

void display(){ node *temp; temp=head; if (rare < 0) { cout <<" queue under flow"; return; } while(temp != NULL) { cout <<temp->data<< " "; temp=temp->next; }

} void pop() {

node *temp;temp=head;if( rare < 0){cout <<"queue under flow";return;}if(front == rare){front = rare =-1;

head=NULL;return;} front++;head=head->next;

}

};void main(){

queue s1;int ch;

28

Page 29: Advanced c c++

Advanced C Programming

clrscr();while(1){

cout <<"\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n enter ru choice:";cin >> ch;switch(ch){case 1:

cout <<"\n enter a element";cin >> ch;s1.push(ch);break;

case 2: s1.pop();break;case 3: s1.display();

break;case 4: exit(0);}

}}

OUTPUT

1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:1 enter a element23

1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:1 enter a element54

1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:323 541.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:2

1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:2

1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:2queue under flow1.PUSH 2.POP 3.DISPLAY 4.EXIT enter ru choice:4

29

Page 30: Advanced c c++

Advanced C Programming

Algorithms fo DeQueue Using Double Linked ListAlgorithm Insertfirst(item){ if dequeue is empty {

Item-next=item-prev=NULL;tail=head=item;

}else if(dequeue is full) print” insertion is not possible”else {

item-next=head;item-prev=NULL;head=item;

}}

Algorithm Insertlast (item){ if dequeue is empty {

Item-next=item-prev=NULL;tail=head=item;

}else if(dequeue is full) print” insertion is not possible”else {

tail-next=head;item-prev=tail;tail=item;

}}

Deletefirst(){If (dequeue is empty) print” no node to delete”;else{Head=head-next;Head-prev=NULL;}}

30

Page 31: Advanced c c++

Advanced C Programming

Deletelast(){if (dequeue is empty) print” no node to delete”;else{tail=tail-prev;tail-next=NULL;}}

Displayfirst(){if( dequeue is empty) print “ no node to display”else{temp=head;while(temp-next!=null) then do {

print(temp-data);temp=temp-next;

}}}

Displaylast(){if( dequeue is empty) print “ no node to display”else{temp=tailwhile(temp-prevt!=null) then do {

print(temp-data);temp=temp-prev;

}}}

31

Page 32: Advanced c c++

Advanced C Programming

Implementation of DeQueue Using Double Linked List

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

class node{ public:

int data;class node *next;class node *prev;

};

class dqueue: public node{ node *head,*tail;

int top1,top2; public: dqueue() { top1=0; top2=0;

head=NULL;tail=NULL;

}

void push(int x){

node *temp;int ch;if(top1+top2 >=5){

cout <<"dqueue overflow"; return ;

}if( top1+top2 == 0) {

head = new node; head->data=x; head->next=NULL; head->prev=NULL; tail=head; top1++;

}

32

Page 33: Advanced c c++

Advanced C Programming

else {

cout <<" Add element 1.FIRST 2.LAST\n enter ur choice:"; cin >> ch; if(ch==1) {

top1++; temp=new node; temp->data=x; temp->next=head;

temp->prev=NULL; head->prev=temp; head=temp; } else { top2++; temp=new node; temp->data=x; temp->next=NULL; temp->prev=tail; tail->next=temp; tail=temp; }

} } void pop() { int ch; cout <<"Delete 1.First Node 2.Last Node\n Enter ur choice:";

cin >>ch;if(top1 + top2 <=0){ cout <<"\nDqueue under flow"; return;} if(ch==1){ head=head->next; head->prev=NULL; top1--;} else

33

Page 34: Advanced c c++

Advanced C Programming

{ top2--; tail=tail->prev; tail->next=NULL;

} }

void display() {

int ch;node *temp;cout <<"display from 1.Staring 2.Ending\n Enter ur choice";cin >>ch;if(top1+top2 <=0) { cout <<"under flow";

return ; }

if (ch==1) {

temp=head; while(temp!=NULL) { cout << temp->data <<" "; temp=temp->next; }

}else{ temp=tail;

while( temp!=NULL){

cout <<temp->data << " ";temp=temp->prev;

} }

} };

void main() { dqueue d1;

int ch;clrscr();

while (1)

34

Page 35: Advanced c c++

Advanced C Programming

{cout <<"1.INSERT 2.DELETE 3.DISPLAU 4.EXIT\n Enter ur choice:";cin >>ch; switch(ch){

case 1: cout <<"enter element"; cin >> ch; d1.push(ch); break;

case 2: d1.pop(); break;case 3: d1.display(); break;case 4: exit(1);

} }}

OUTPUT1.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:1enter element41.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:1enter element5 Add element 1.FIRST 2.LAST enter ur choice:11.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:1enter element6 Add element 1.FIRST 2.LAST enter ur choice:21.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:3display from 1.Staring 2.Ending Enter ur choice15 4 6 1.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:2Delete 1.First Node 2.Last Node Enter ur choice:11.INSERT 2.DELETE 3.DISPLAU 4.EXIT Enter ur choice:3display from 1.Staring 2.Ending Enter ur choice14 6 1.INSERT 2.DELETE 3.DISPLAU 4.EXIT

Enter ur choice:4

35

Page 36: Advanced c c++

Advanced C Programming

Algorithm for Circular Queue Algorithm Insertfirst(item)

{

if cqueue is empty then head=item;

else if(cqueue is full) print” insertion is not possible”

else

{

Rear=(rear +1) mod max

} cqueue[rear]=x;

}

Algorithm Deletet()

{

If (dequeue is empty) print” no node to delete”;

else

{

Front=(front+1) mod max

}

}

Algorithm display()

{

If (front >rear) display elements for front to max and 0 to rear

Else display elements from front to rear

}

36

Page 37: Advanced c c++

Advanced C Programming

Implementation of Circular Queue Using Array

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

class cqueue{ int q[5],front,rare; public: cqueue() {

front=-1; rare=-1;

}

void push(int x) {

if(front ==-1 && rare == -1) {

q[++rare]=x; front=rare; return;

} else if(front == (rare+1)%5 ) {

cout <<" Circular Queue over flow"; return;

} rare= (rare+1)%5; q[rare]=x;

}

void pop() {

if(front==-1 && rare== -1){

cout <<"under flow"; return;

}else if( front== rare ){

front=rare=-1; return;

37

Page 38: Advanced c c++

Advanced C Programming

}front= (front+1)%5;

} void display()

{int i;if( front <= rare)

{for(i=front; i<=rare;i++)cout << q[i]<<" ";

} else {

for(i=front;i<=4;i++) { cout <<q[i] << " "; } for(i=0;i<=rare;i++) { cout << q[i]<< " "; }

} }};

void main(){

int ch;cqueue q1;clrscr();while( 1){cout<<"\n1.INSERT 2.DELETE 3.DISPLAY 4.EXIT\nEnter ur choice";cin >> ch;switch(ch){

case 1: cout<<"enter element";cin >> ch;q1.push(ch); break;

case 2: q1.pop(); break;case 3: q1.display(); break;case 4: exit(0);

}}}

38

Page 39: Advanced c c++

Advanced C Programming

OUTPUT

1.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice1enter element4

1.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice1enter element5

1.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice1enter element3

1.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice34 5 31.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice2

1.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice35 31.INSERT 2.DELETE 3.DISPLAY 4.EXITEnter ur choice4

39

Page 40: Advanced c c++

Advanced C Programming

Algorithm for Dictionary

Program to Implement Functions of a Dictionary

#include<iostream.h>#include<conio.h>#include<stdlib.h># define max 10

typedef struct list{

int data;struct list *next;

}node_type;node_type *ptr[max],*root[max],*temp[max];

class Dictionary{

public:int index;Dictionary();void insert(int);void search(int);void delete_ele(int);

};

Dictionary::Dictionary(){

index=-1;for(int i=0;i<max;i++){

root[i]=NULL;ptr[i]=NULL;temp[i]=NULL;

}}

void Dictionary::insert(int key){

index=int(key%max);ptr[index]=(node_type*)malloc(sizeof(node_type));ptr[index]->data=key;if(root[index]==NULL)

40

Page 41: Advanced c c++

Advanced C Programming

{root[index]=ptr[index];root[index]->next=NULL;temp[index]=ptr[index];}else{

temp[index]=root[index];while(temp[index]->next!=NULL)temp[index]=temp[index]->next;temp[index]->next=ptr[index];

}}

void Dictionary::search(int key){

int flag=0;index=int(key%max);temp[index]=root[index];while(temp[index]!=NULL){

if(temp[index]->data==key){cout<<"\nSearch key is found!!";flag=1;break;}else temp[index]=temp[index]->next;

}if (flag==0)cout<<"\nsearch key not found.......";

}

void Dictionary::delete_ele(int key){

index=int(key%max);temp[index]=root[index];while(temp[index]->data!=key && temp[index]!=NULL){

ptr[index]=temp[index];temp[index]=temp[index]->next;

}ptr[index]->next=temp[index]->next;cout<<"\n"<<temp[index]->data<<" has been deleted.";

41

Page 42: Advanced c c++

Advanced C Programming

temp[index]->data=-1;temp[index]=NULL;free(temp[index]);

}

void main(){

int val,ch,n,num;char c;Dictionary d;clrscr();do{

cout<<"\nMENU:\n1.Create";cout<<"\n2.Search for a value\n3.Delete an value";cout<<"\nEnter your choice:";cin>>ch;switch(ch){

case 1: cout<<"\nEnter the number of elements to be inserted:";cin>>n;

cout<<"\nEnter the elements to be inserted:";for(int i=0;i<n;i++){

cin>>num;d.insert(num);

}break;

case 2: cout<<"\nEnter the element to be searched:";cin>>n;d.search(n);

case 3: cout<<"\nEnter the element to be deleted:";cin>>n;d.delete_ele(n);break;

default: cout<<"\nInvalid choice....";}

cout<<"\nEnter y to continue......";cin>>c;

}while(c=='y');getch();}

42

Page 43: Advanced c c++

Advanced C Programming

43

Page 44: Advanced c c++

Advanced C Programming

OUTPUTMENU:1.Create2.Search for a value3.Delete an valueEnter your choice:1

Enter the number of elements to be inserted:8

Enter the elements to be inserted:10 4 5 8 7 12 6 1

Enter y to continue......y

MENU:1.Create2.Search for a value3.Delete an valueEnter your choice:2

Enter the element to be searched:12

Search key is found!!Enter the element to be deleted:1

1 has been deleted.Enter y to continue......y

44

Page 45: Advanced c c++

Advanced C Programming

AVL TREEAlgorithm insertion(int x){If(tree is empty) then root is emptyOtherwise {temp=search(item); // temp is the node where search for the

item haltsif( item > temp) then temp-right=item;otherwise temp-left =item

Reconstruction procedure: rotating tree left rotation and right rotation Suppose that the rotation occurs at node x Left rotation: certain nodes from the right subtree of x

move to its left subtree; the root of the right subtree of x becomes the new root of the reconstructed subtree

Right rotation at x: certain nodes from the left subtree of x move to its right subtree; the root of the left subtree of x becomes the new root of the reconstructed subtree

}

Algorithm Search(int x)Algorithm delete(){

Case 1: the node to be deleted is a leaf Case 2: the node to be deleted has no right child, that

is, its right subtree is empty Case 3: the node to be deleted has no left child, that

is, its left subtree is empty Case 4: the node to be deleted has a left child and a

right child}

Algorithm Search(x, root){if(tree is empty ) then print” tree is empty”otherwise If(x grater than root) search(root-right);Otherwise if(x less than root ) search(root-left)Otherwise return true}}

45

Page 46: Advanced c c++

Advanced C Programming

AVL TREE

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

void insert(int,int );void delte(int);void display(int);int search(int);int search1(int,int);

int avltree[40],t=1,s,x,i;

void main(){

int ch,y;for(i=1;i<40;i++)avltree[i]=-1;while(1){

cout <<"1.INSERT\n2.DELETE\n3.DISPLAY\n4.SEARCH\n5.EXIT\nEnter your choice:";cin >> ch;switch(ch){case 1:

cout <<"enter the element to insert";cin >> ch;insert(1,ch);break;

case 2:cout <<"enter the element to delete";cin >>x;y=search(1);if(y!=-1) delte(y);else cout<<"no such element in avlavltree";break;

case 3:display(1);cout<<"\n";for(int i=0;i<=32;i++)cout <<i;cout <<"\n";break;

46

Page 47: Advanced c c++

Advanced C Programming

case 4:cout <<"enter the element to search:";cin >> x;y=search(1);if(y == -1) cout <<"no such element in avltree";else cout <<x << "is in" <<y <<"position";break;

case 5:exit(0);

}}

}

void insert(int s,int ch ){

int x,y;if(t==1){

avltree[t++]=ch;return;

}x=search1(s,ch);if(avltree[x]>ch) { avltree[2*x]=ch;

y=log(2*x)/log(2);if(height(1,y)){if( x%2==0 ) update1(); else update2();}

}else {

avltree[2*x+1]=ch; y=log(2*x)/log(2);if(height(1,y)){if(x%2==1) update1();else update2();}

}

47

Page 48: Advanced c c++

Advanced C Programming

t++;}void delte(int x){

if( avltree[2*x]==-1 && avltree[2*x+1]==-1)avltree[x]=-1;

else if(avltree[2*x]==-1) { avltree[x]=avltree[2*x+1];

avltree[2*x+1]=-1; }else if(avltree[2*x+1]==-1) { avltree[x]=avltree[2*x];

avltree[2*x]=-1; }else{ avltree[x]=avltree[2*x]; delte(2*x);}t--;

}int search(int s){

if(t==1){

cout <<"no element in avltree";return -1;

}if(avltree[s]==-1)

return avltree[s];if(avltree[s]>x)

search(2*s);else if(avltree[s]<x)

search(2*s+1);else

return s;}

void display(int s){

if(t==1){

cout <<"no element in avltree:";return;}

48

Page 49: Advanced c c++

Advanced C Programming

for(int i=1;i<40;i++)if(avltree[i]==-1)cout <<" ";else cout <<avltree[i];return ;

}

int search1(int s,int ch){

if(t==1){

cout <<"no element in avltree";return -1;

}if(avltree[s]==-1)return s/2;if(avltree[s] > ch)search1(2*s,ch);else search1(2*s+1,ch);

}

int height(int s,int y){

if(avltree[s]==-1)return;

}

49

Page 50: Advanced c c++

Advanced C Programming

OUTPUT

1.insert 2.display 3.delete 4.search 5.exitEnter u r choice to perform on AVL tree1Enter an element to insert into tree4

do u want to continuey

1.insert 2.display 3.delete 4.search 5.exitEnter u r choice to perform on AVL tree1Enter an element to insert into tree5

do u want to continuey

1.insert 2.display 3.delete 4.search 5.exitEnter u r choice to perform on AVL tree3

Enter an item to deletion5

itemfounddo u want to continuey

1.insert 2.display 3.delete 4.search 5.exitEnter u r choice to perform on AVL tree24do u want to continue4

50

Page 51: Advanced c c++

Advanced C Programming

Breath First Search AlgorithmAlgorithm BFS(s): Input: A vertex s in a graph

Output: A labeling of the edges as “discovery” edges and “cross

edges”

initialize container L0 to contain vertex s

i ¬ 0

while Li is not empty do

create container Li+1 to initially be empty

for each vertex v in Li do

if edge e incident on v do

let w be the other endpoint of e

if vertex w is unexplored then

label e as a discovery edge

insert w into Li+1

else label e as a cross edge

i ¬ i + 1

51

Page 52: Advanced c c++

Advanced C Programming

Breath First Search Implementation

#include<iostream.h>#include<conio.h>#include<stdlib.h>int cost[10][10],i,j,k,n,qu[10],front,rare,v,visit[10],visited[10];

void main(){

clrscr();int m;cout <<"enterno of vertices";cin >> n;cout <<"ente no of edges";cin >> m;cout <<"\nEDGES \n";for(k=1;k<=m;k++){

cin >>i>>j;cost[i][j]=1;

}

cout <<"enter initial vertex";cin >>v;cout <<"Visitied vertices\n";cout << v;xvisited[v]=1;k=1;while(k<n){

for(j=1;j<=n;j++)if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1){visit[j]=1;qu[rare++]=j;}

v=qu[front++];cout<<v << " ";k++;visit[v]=0; visited[v]=1;

}}

OUTPUT

52

Page 53: Advanced c c++

Advanced C Programming

enterno of vertices9ente no of edges9

EDGES1 22 31 51 44 77 88 92 65 7enter initial vertex1Visited vertices12 4 5 3 6 7 8 9

53

Page 54: Advanced c c++

Advanced C Programming

Depth First Search Algorithm

Algorithm DFS(v); Input: A vertex v in a graph

Output: A labeling of the edges as “discovery” edges and

“backedges”

for each edge e incident on v do

if edge e is unexplored then let w be the other

endpoint of e

if vertex w is unexplored then label e as a discovery

edge recursively call DFS(w)

else label e as a backedge

54

Page 55: Advanced c c++

Advanced C Programming

Depth First Search

#include<iostream.h>#include<conio.h>#include<stdlib.h>int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];

void main(){

int m;clrscr();cout <<"enterno of vertices";cin >> n;cout <<"ente no of edges";cin >> m;cout <<"\nEDGES \n";for(k=1;k<=m;k++){

cin >>i>>j;cost[i][j]=1;

}

cout <<"enter initial vertex";cin >>v;cout <<"ORDER OF VISITED VERTICES";cout << v <<" ";visited[v]=1;k=1;while(k<n){

for(j=n;j>=1;j--)if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1){

visit[j]=1;stk[top]=j;top++;

}v=stk[--top];cout<<v << " ";k++;visit[v]=0; visited[v]=1;

}}

55

Page 56: Advanced c c++

Advanced C Programming

OUTPUTenterno of vertices9ente no of edges9

EDGES1 22 32 61 51 44 75 77 88 9enter initial vertex1ORDER OF VISITED VERTICES1 2 3 6 4 7 8 9 5

56

Page 57: Advanced c c++

Advanced C Programming

Prim’s AlgorithmAlgorithm Prim(E,Cost,n,t)

{

Let (k, l) be an edge of minimum cost in E;

Mincost= cost[k,l];

t[1,1]=k;

t[1,2]=l;

for i=1 to n do

{

If (cost[i, l]<cost[k,l]) then near[i]=l;

Else

Near[i]=k;

Near[k]=near[j]=0;

}

For i=2 to n -1 do

{

Let j be an index such that nearpj]!= 0 and cost[j,near[j]]

is minimum

T[I,1]=j ; t[I,2]=near[j]

mincost=mincost + cost[j,near[j]];

near[j]=0;

for k=1 to n do

if(near[k] !=0 ) and cost[k,near[k]]) >cost[k,j])

then near[j]=k

}

}

57

Page 58: Advanced c c++

Advanced C Programming

Prim’s Algorithm

#include<iostream.h>#include<conio.h>#include<stdlib.h>int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10],u;

void main(){

int m,c;clrscr();cout <<"enterno of vertices";cin >> n;cout <<"ente no of edges";cin >> m;cout <<"\nEDGES Cost\n";for(k=1;k<=m;k++){

cin >>i>>j>>c;cost[i][j]=c;

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

if(cost[i][j]==0)cost[i][j]=31999;

cout <<"ORDER OF VISITED VERTICES";k=1;while(k<n){

m=31999;if(k==1){

for(i=1;i<=n;i++)for(j=1;j<=m;j++)if(cost[i][j]<m){

m=cost[i][j];u=i;

}}else{

for(j=n;j>=1;j--)if(cost[v][j]<m && visited[j]!=1 && visit[j]!=1)

58

Page 59: Advanced c c++

Advanced C Programming

{visit[j]=1;stk[top]=j;top++;m=cost[v][j];u=j;

}}cost[v][u]=31999;v=u;cout<<v << " ";k++;visit[v]=0; visited[v]=1;

}}

OUTPUTenterno of vertices7ente no of edges9

EDGES Cost1 6 10 6 5 255 4 224 3 123 2 16 2 7 14 5 7 24 4 7 18 1 2 28ORDER OF VISITED VERTICES1 6 5 4 3 2

59

Page 60: Advanced c c++

Advanced C Programming

Kruskal’s Algorithm

Algorithm Krushkal(E, cost,n,t)

{

for i=1 to n do parent[i]=-1;

i=0;

mincost=0;

while( I < n-1)

{

Delete a minimum coast edge (u,v) form the heap and

reheapfy using adjust

J=find(u);

K=find(v);

If(j!=k) then

{

i=i+1;

t[I,1]=u; t[I,2]=v;

mincost=mincost+ cost[u,v];

union(j,k)

}

If( i != n-1) the write (“ no spanning tree”);

else

Return mincost

}

}

60

Page 61: Advanced c c++

Advanced C Programming

Kruskal’s Algorithm

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

int cost[10][10],i,j,k,n,m,c,visit,visited[10],l,v,count,count1,vst,p;main(){

int dup1,dup2;cout<<"enter no of vertices";cin >> n;cout <<"enter no of edges";cin >>m;cout <<"EDGE Cost";for(k=1;k<=m;k++){

cin >>i >>j >>c;cost[i][j]=c;cost[j][i]=c;

}for(i=1;i<=n;i++)for(j=1;j<=n;j++)if(cost[i][j]==0)cost[i][j]=31999;visit=1;while(visit<n){

v=31999;for(i=1;i<=n;i++)for(j=1;j<=n;j++)if(cost[i][j]!=31999 && cost[i][j]<v && cost[i][j]!=-1 ){count =0;for(p=1;p<=n;p++){

if(visited[p]==i || visited[p]==j)count++;

}if(count >= 2){

for(p=1;p<=n;p++)if(cost[i][p]!=31999 && p!=j)dup1=p;

61

Page 62: Advanced c c++

Advanced C Programming

for(p=1;p<=n;p++)if(cost[j][p]!=31999 && p!=i)dup2=p;if(cost[dup1][dup2]==-1)

continue;}l=i;k=j;v=cost[i][j];

}cout <<"edge from " <<l <<"-->"<<k;cost[l][k]=-1;cost[k][l]=-1;visit++;count=0;count1 =0;for(i=1;i<=n;i++){if(visited[i]==l)

count++;if(visited[i]==k)count1++;

}

if(count==0)visited[++vst]=l;if(count1==0)visited[++vst]=k;}}

62

Page 63: Advanced c c++

Advanced C Programming

Single Source Shortest Path

#include<iostream.h>#include<conio.h>#include<stdio.h>int shortest(int ,int);int cost[10][10],dist[20],i,j,n,k,m,S[20],v,totcost,path[20],p;void main(){int c;clrscr();cout <<"enter no of vertices";cin >> n;cout <<"enter no of edges";

cin >>m;cout <<"\nenter\nEDGE Cost\n";for(k=1;k<=m;k++){cin >> i >> j >>c;cost[i][j]=c;}for(i=1;i<=n;i++)for(j=1;j<=n;j++)if(cost[i][j]==0)cost[i][j]=31999;cout <<"enter initial vertex";cin >>v;cout << v<<"\n";shortest(v,n);

}

shortest(int v,int n){int min;

for(i=1;i<=n;i++){S[i]=0;dist[i]=cost[v][i];}path[++p]=v;

63

Page 64: Advanced c c++

Advanced C Programming

S[v]=1;dist[v]=0;

for(i=2;i<=n-1;i++){k=-1;min=31999;for(j=1;j<=n;j++){if(dist[j]<min && S[j]!=1){min=dist[j];k=j;}

}if(cost[v][k]<=dist[k])p=1;

path[++p]=k;

for(j=1;j<=p;j++)cout<<path[j];cout <<"\n";//cout <<k;S[k]=1;for(j=1;j<=n;j++)if(cost[k][j]!=31999 && dist[j]>=dist[k]+cost[k][j] && S[j]!=1) dist[j]=dist[k]+cost[k][j];}}

OUTPUTenter no of vertices6enter no of edges11

enterEDGE Cost1 2 501 3 451 4 102 3 102 4 153 5 304 1 10

64

Page 65: Advanced c c++

Advanced C Programming

4 5 155 2 205 3 356 5 3enter initial vertex1114145145213

65

Page 66: Advanced c c++

Advanced C Programming

Non recursive Pre order Traversing Algorithm

Algorithm preorder( root)

{

1. current = root; //start the traversal at the root node

2. while(current is not NULL or stack is nonempty)

if(current is not NULL)

{

visit current;

push current onto stack;

current = current->llink;

}

else

{

pop stack into current;

current = current->rlink; //prepare to visit

//the right subtree

}

66

Page 67: Advanced c c++

Advanced C Programming

Non recursive Pre order Traversing

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

class node{public:class node *left;class node *right;int data;};

class tree: public node{public:int stk[50],top;node *root;tree(){root=NULL;top=0;}void insert(int ch){

node *temp,*temp1;if(root== NULL){

root=new node;root->data=ch;root->left=NULL;root->right=NULL;return;

}temp1=new node;temp1->data=ch;temp1->right=temp1->left=NULL;temp=search(root,ch);if(temp->data>ch)

temp->left=temp1;else

temp->right=temp1;

}

67

Page 68: Advanced c c++

Advanced C Programming

node *search(node *temp,int ch){

if(root== NULL){

cout <<"no node present";return NULL;

}if(temp->left==NULL && temp->right== NULL)

return temp;

if(temp->data>ch) { if(temp->left==NULL) return temp;

search(temp->left,ch);}else { if(temp->right==NULL) return temp; search(temp->right,ch);

} }

void display(node *temp){

if(temp==NULL) return ;display(temp->left);

cout<<temp->data <<" ";display(temp->right);

}void preorder( node *root){

node *p,*q;p=root;q=NULL;top=0;

while(p!=NULL){

cout <<p->data << " ";if(p->right!=NULL){

stk[top]=p->right->data;top++;

}p=p->left;if(p==NULL && top>0)

{

68

Page 69: Advanced c c++

Advanced C Programming

p=pop(root);}}

}node * pop(node *p){int ch;ch=stk[top-1];if(p->data==ch){top--;return p;}if(p->data>ch)pop(p->left);elsepop(p->right);}};void main(){

tree t1;int ch,n,i;while(1){

cout <<"\n1.INSERT\n2.DISPLAY 3.PREORDER TRAVERSE\n4.EXIT\nEnter your choice:";

cin >> ch;switch(ch){case 1: cout <<"enter no of elements to insert:";

cout<<"\n enter the elements"; cin >> n; for(i=1;i<=n;i++) { cin >> ch; t1.insert(ch); } break;

case 2: t1.display(t1.root);break;case 3: t1.preorder(t1.root); break;case 4: exit(1);}

}}

OUTPUT

69

Page 70: Advanced c c++

Advanced C Programming

1.INSERT2.DISPLAY 3.PREORDER TRAVERSE4.EXITEnter your choice:1enter no of elements to insert enter the elements75 24 36 11 44 2 21

1.INSERT2.DISPLAY 3.PREORDER TRAVERSE4.EXITEnter your choice:22 5 11 21 24 36 441.INSERT2.DISPLAY 3.PREORDER TRAVERSE4.EXITEnter your choice:35 2 24 11 21 36 441.INSERT2.DISPLAY 3.PREORDER TRAVERSE4.EXITEnter your choice:4

70

Page 71: Advanced c c++

Advanced C Programming

Non recursive In order TraversingAlgorithm inorder( root)

{

1. current = root; //start traversing the binary tree at

// the root node

2. while(current is not NULL or stack is nonempty)

if(current is not NULL)

{

push current onto stack;

current = current->llink;

}

else

{

pop stack into current;

visit current; //visit the node

current = current->rlink; //move to the

//right child

}

}

71

Page 72: Advanced c c++

Advanced C Programming

Non recursive In order Traversing

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

class node{public:class node *left;class node *right;int data;};

class tree: public node{public:int stk[50],top;node *root;tree(){root=NULL;top=0;}void insert(int ch){

node *temp,*temp1;if(root== NULL){

root=new node;root->data=ch;root->left=NULL;root->right=NULL;return;

}temp1=new node;temp1->data=ch;temp1->right=temp1->left=NULL;temp=search(root,ch);if(temp->data>ch)

temp->left=temp1;else

temp->right=temp1;

72

Page 73: Advanced c c++

Advanced C Programming

}

node *search(node *temp,int ch){

if(root== NULL){

cout <<"no node present";return NULL;

}if(temp->left==NULL && temp->right== NULL)

return temp;

if(temp->data>ch) { if(temp->left==NULL) return temp;

search(temp->left,ch);}else { if(temp->right==NULL) return temp; search(temp->right,ch);

} }

void display(node *temp){

if(temp==NULL) return ;display(temp->left);

cout<<temp->data;display(temp->right);

}void inorder( node *root){

node *p;p=root;top=0;do{

while(p!=NULL){

stk[top]=p->data;top++;p=p->left;

}if(top>0){

p=pop(root);

73

Page 74: Advanced c c++

Advanced C Programming

cout << p->data;p=p->right;

}}while(top!=0 || p!=NULL);

}

node * pop(node *p){

int ch;ch=stk[top-1];if(p->data==ch){

top--;return p;

}if(p->data>ch)

pop(p->left);else

pop(p->right);}};

void main(){

tree t1;int ch,n,i;while(1){

cout <<"\n1.INSERT\n2.DISPLAY 3.INORDER TRAVERSE\n4.EXIT\nEnter your choice:";

cin >> ch;switch(ch){case 1: cout <<"enter no of elements to insert:";

cin >> n; for(i=1;i<=n;i++) { cin >> ch; t1.insert(ch); } break;

case 2: t1.display(t1.root);break;case 3: t1.inorder(t1.root); break;case 4: exit(1);}

}

74

Page 75: Advanced c c++

Advanced C Programming

}

OUTPUT1.INSERT2.DISPLAY 3.INORDER TRAVERSE4.EXITEnter your choice:1enter no of elements to inser5 24 36 11 44 2 21

1.INSERT2.DISPLAY 3.INORDER TRAVERSE4.EXITEnter your choice:32511212436441.INSERT2.DISPLAY 3.INORDER TRAVERSE4.EXITEnter your choice:32511212436441.INSERT2.DISPLAY 3.INORDER TRAVERSE4.EXITEnter your choice:4

75

Page 76: Advanced c c++

Advanced C Programming

Non recursive Post order Traversing AlgorithmAlgorithm postorder( node root)

{

1. current = root; //start traversal at root node

2. v = 0;

3. if(current is NULL)

the binary tree is empty

4. if(current is not NULL)

a. push current into stack;

b. push 1 onto stack;

c. current = current->llink;

d. while(stack is not empty)

if(current is not NULL and v is 0)

{

push current and 1 onto stack;

current = current->llink;

}

else

{

pop stack into current and v;

if(v == 1)

{

push current and 2 onto stack;

current = current->rlink;

v = 0;

}

else

visit current;

}}

76

Page 77: Advanced c c++

Advanced C Programming

Non recursive Post order Traversing

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

class node{public:class node *left;class node *right;int data;};

class tree: public node{public:int stk[50],top;node *root;tree(){root=NULL;top=0;}void insert(int ch){

node *temp,*temp1;if(root== NULL){

root=new node;root->data=ch;root->left=NULL;root->right=NULL;return;

}temp1=new node;temp1->data=ch;temp1->right=temp1->left=NULL;temp=search(root,ch);if(temp->data>ch)

temp->left=temp1;else

temp->right=temp1;

77

Page 78: Advanced c c++

Advanced C Programming

}

node *search(node *temp,int ch){

if(root== NULL){

cout <<"no node present";return NULL;

}if(temp->left==NULL && temp->right== NULL)

return temp;

if(temp->data>ch) { if(temp->left==NULL) return temp;

search(temp->left,ch);}else { if(temp->right==NULL) return temp; search(temp->right,ch);

} }

void display(node *temp){

if(temp==NULL) return ;display(temp->left);

cout<<temp->data << " ";display(temp->right);

}void postorder( node *root){

node *p;p=root;top=0;

while(1){while(p!=NULL){

stk[top]=p->data;top++;if(p->right!=NULL)

stk[top++]=-p->right->data;p=p->left;

}

78

Page 79: Advanced c c++

Advanced C Programming

while(stk[top-1] > 0 || top==0){ if(top==0) return; cout << stk[top-1] <<" "; p=pop(root);}if(stk[top-1]<0){ stk[top-1]=-stk[top-1]; p=pop(root);

} }

}node * pop(node *p){int ch;ch=stk[top-1];if(p->data==ch){top--;return p;}if(p->data>ch)pop(p->left);elsepop(p->right);}};void main(){

tree t1;int ch,n,i;clrscr();while(1){

cout <<"\n1.INSERT\n2.DISPLAY 3.POSTORDER TRAVERSE\n4.EXIT\nEnter your choice:";

cin >> ch;switch(ch){case 1: cout <<"enter no of elements to insert:";

cout<<"\n enter the elements"; cin >> n; for(i=1;i<=n;i++) { cin >> ch; t1.insert(ch);

79

Page 80: Advanced c c++

Advanced C Programming

} break;

case 2: t1.display(t1.root);break;case 3: t1.postorder(t1.root); break;case 4: exit(1);}

}}

OUTPUT1.INSERT2.DISPLAY 3.POSTORDER TRAVERSE4.EXITEnter your choice:1enter no of elements to insert: enter the elements75 24 36 11 44 2 21

1.INSERT2.DISPLAY 3.POSTORDER TRAVERSE4.EXITEnter your choice:22 5 11 21 24 36 441.INSERT2.DISPLAY 3.POSTORDER TRAVERSE4.EXITEnter your choice:32 21 11 44 36 24 51.INSERT2.DISPLAY 3.POSTORDER TRAVERSE4.EXITEnter your choice:4

80

Page 81: Advanced c c++

Advanced C Programming

Quick Sort Algorithm

Algorithm quicksort(a[],p,q)

{

V=a[p];

i=p;

j=q;

if(i<j)

{

repeat

{

repeat

I=i+1;

Until( a[i]> v);

Repeat

J=j-1;

Until(a[j]<v);

If(i<j) then interchange ( a[i],a[j])

}until (i<=j);

interchange(a[j], a[p])

}

quicksort(a[],p,j);

quicksort(a[],j+1,q);

}

81

Page 82: Advanced c c++

Advanced C Programming

Quick Sort

#include<iostream.h>#include<conio.h>int a[10],l,u,i,j;void quick(int *,int,int);void main(){clrscr();cout <<"enter 10 elements";for(i=0;i<10;i++)cin >> a[i];l=0;u=9;quick(a,l,u);cout <<"sorted elements";for(i=0;i<10;i++)cout << a[i] << " ";getch();}

void quick(int a[],int l,int u){ int p,temp; if(l<u) { p=a[l]; i=l; j=u; while(i<j) {

while(a[i] <= p && i<j ) i++;

while(a[j]>p && i<=j ) j--;

if(i<=j) { temp=a[i]; a[i]=a[j]; a[j]=temp;} } temp=a[j]; a[j]=a[l];

82

Page 83: Advanced c c++

Advanced C Programming

a[l]=temp; cout <<"\n"; for(i=0;i<10;i++) cout <<a[i]<<" ";

quick(a,l,j-1); quick(a,j+1,u); }}

OUTPUTenter 10 elements5 2 3 16 25 1 20 7 8 61 14

1 2 3 5 25 16 20 7 8 611 2 3 5 25 16 20 7 8 611 2 3 5 25 16 20 7 8 611 2 3 5 25 16 20 7 8 611 2 3 5 25 16 20 7 8 611 2 3 5 8 16 20 7 25 611 2 3 5 7 8 20 16 25 611 2 3 5 7 8 16 20 25 611 2 3 5 7 8 16 20 25 61 sorted elements1 2 3 5 7 8 16 20 25 61

83

Page 84: Advanced c c++

Advanced C Programming

Merge Sort Algorithm

Algorithm Mergesort(low,high){If(low<high){

Mid=(low+high)/2;Mergesort(low,mid);Mergesort(mid+1,high)Merge(low,mid,high);

}}

Algorithm Merge(low,mid,high){h=low; i=low; j=mid+1;While(h<=mid and j<=high) do{

If(a[h]<a[j]) then{

b[i]=a[h];h=h+1;}else{

b[i]=a[j];J=j+1;

}if(h>mid)

{For k= j to high do

b[i]=a[k]; i=i+1;}Else{

For k=h to mid do b[i]=a[k]; i=i+1;

}For k= low to high do a[k]=b[k];

}}

84

Page 85: Advanced c c++

Advanced C Programming

Merge Sort

Merge Sort

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

void mergesort(int *,int,int);void merge(int *,int,int,int);

int a[20],i,n,b[20];

void main(){

clrscr();cout <<"\N enter no of elements";cin >> n;cout <<"enter the elements";for(i=0;i<n;i++)cin >> a[i];mergesort(a,0,n-1);cout <<" numbers after sort";for(i=0;i<n;i++)cout << a[i] << " ";getch();

}

void mergesort(int a[],int i,int j){ int mid;

if(i<j){ mid=(i+j)/2; mergesort(a,i,mid); mergesort(a,mid+1,j); merge(a,i,mid,j);}

}

void merge(int a[],int low,int mid ,int high){ int h,i,j,k;

h=low;i=low;

85

Page 86: Advanced c c++

Advanced C Programming

j=mid+1; while(h<=mid && j<=high)

{ if(a[h]<=a[j])

b[i]=a[h++];else b[i]=a[j++];

i++; }

if( h > mid) for(k=j;k<=high;k++)

b[i++]=a[k]; else for(k=h;k<=mid;k++)

b[i++]=a[k]; cout <<"\n"; for(k=low;k<=high;k++) {

a[k]=b[k]; cout << a[k] <<" "; }

}

OUTPUTN enter no of elements8 12 5 61 60 50 1 70 81enter the elements5 1260 615 12 60 611 5070 811 50 70 811 5 12 50 60 61 70 81 numbers after sort1 5 12 50 60 61 70 81

86

Page 87: Advanced c c++

Advanced C Programming

Heap Sort Algorithm

Definition: A heap is a list in which each element contains a key, such that the key in the element at position k in the list is at least as large as the key in the element at position 2k + 1 (if it exists), and 2k + 2 (if it exists)

Algorithm Heapify(a[],n)

{

For i=n/2 to 1 step -1

Adjustify (a,i,n);

}

Algorithm Adjustify(a[],i,n)

{

Repeat

{

J=leftchild(i)

Compare left and right child of a[i] and store the index of grater number in j

Compare a[j] and a[i]

If (a[j]>a[i]) then

Copy a[j] to a[i] and move to next level

}until(j<n)

}

87

Page 88: Advanced c c++

Advanced C Programming

Heap Sort

#include<stdio.h>#include<conio.h>int a[20],n;main(){

int i,j,temp;clrscr();printf("ente n");scanf("%d",&n);printf("enter the elements");

for(i=1;i<=n;i++)scanf("%d",&a[i]);

heapify(a,n);for(j=1;j<=n;j++)

printf("%d",a[j]);

for(i=n;i>=2;i--){

temp=a[i];a[i]=a[1];a[1]=temp;adjust(a,1,i-1);printf("\n");for(j=1;j<=n;j++)printf("%d ",a[j]);

}printf("\nelements after sort");for(i=1;i<=n;i++)

printf("%d ",a[i]);}

heapify(int a[],int n){

int i;for( i=n/2;i>=1;i--)

adjust(a,i,n);}

88

Page 89: Advanced c c++

Advanced C Programming

adjust(int a[],int i,int n){

int j,iteam;j=2*i;iteam=a[i];while(j<=n){

if(j<n && a[j]<a[j+1])j=j+1;if(iteam>=a[j])

break;a[j/2]=a[j]; j=2*j;

}a[j/2]=iteam;

}

89

Page 90: Advanced c c++

Advanced C Programming

All Paris Shortest Path

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

int min(int a,int b);

int cost[10][10],a[10][10],i,j,k,c;

void main(){ int n,m; cout <<"enter no of vertices"; cin >> n; cout <<"enter no od edges"; cin >> m; cout<<"enter the\nEDGE Cost\n";for(k=1;k<=m;k++){cin>>i>>j>>c;a[i][j]=cost[i][j]=c;}for(i=1;i<=n;i++)for(j=1;j<=n;j++){if(a[i][j]== 0 && i !=j)a[i][j]=31999;}for(k=1;k<=n;k++)for(i=1;i<=n;i++)for(j=1;j<=n;j++)a[i][j]=min(a[i][j],a[i][k]+a[k][j]);

cout <<"Resultant adj matrix\n";for(i=1;i<=n;i++){for( j=1;j<=n;j++) { if(a[i][j] !=31999) cout << a[i][j] <<" "; }cout <<"\n";}getch();

90

Page 91: Advanced c c++

Advanced C Programming

}

int min(int a,int b){if(a<b)return a;elsereturn b;

}

OUTPUTenter no of vertices3enter no od edges5enter theEDGE Cost1 2 42 1 61 3 113 1 32 3 2Resultant adj matrix0 4 65 0 23 7 0

91

Page 92: Advanced c c++

Advanced C Programming

Algorithms for Binary Search TreeAlgorithm Insert(item){

If(tree is empty) then root is emptyOtherwise {temp=search(item); // temp is the node where search for the item haltsif( item > temp) then temp-right=item;otherwise temp-left =item

}}

Algorithm Search(x, root){

if(tree is empty ) then print” tree is empty”otherwise If(x grater than root) search(root-right);Otherwise if(x less than root ) search(root-left)Otherwise return true

}}

Algorithm Delete(x){Search for x in the tree If (not found) print” not found”Otherwise{

If ( x has no child) delete x;If(x has left child) move the left child to x positionIf(x has right child) move the right child to x positionIf(x has both left and right children) replace ‘x’ with greatest of left subtree of ‘x ‘ or smallest of right subtree of ‘x’ and delete selected node in the subtree

} }

92

Page 93: Advanced c c++

Advanced C Programming

Binary Search Tree

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

class node{public:class node *left;class node *right;int data;};

class tree: public node{public:int stk[50],top;node *root;tree(){root=NULL;top=0;}void insert(int ch){

node *temp,*temp1;if(root== NULL){

root=new node;root->data=ch;root->left=NULL;root->right=NULL;return;

}temp1=new node;temp1->data=ch;temp1->right=temp1->left=NULL;temp=search(root,ch);if(temp->data>ch)

temp->left=temp1;else

temp->right=temp1;

}

93

Page 94: Advanced c c++

Advanced C Programming

node *search(node *temp,int ch){

if(root== NULL){

cout <<"no node present";return NULL;

}if(temp->left==NULL && temp->right== NULL)

return temp;

if(temp->data>ch) { if(temp->left==NULL) return temp;

search(temp->left,ch);}else { if(temp->right==NULL) return temp; search(temp->right,ch);

} }

void display(node *temp){

if(temp==NULL) return ;display(temp->left);

cout<<temp->data << " ";display(temp->right);

}

node * pop(node *p){int ch;ch=stk[top-1];if(p->data==ch){top--;return p;}if(p->data>ch)pop(p->left);elsepop(p->right);}};void main()

94

Page 95: Advanced c c++

Advanced C Programming

{tree t1;int ch,n,i;clrscr();while(1){

cout <<"\n1.INSERT\n2.POP\n3.DISPLAY\n4.EXIT\nEnter your choice:";cin >> ch;switch(ch){case 1: cout <<"enter no of elements to insert:";

cout<<"\n enter the elements"; cin >> n; for(i=1;i<=n;i++) { cin >> ch; t1.insert(ch); } break;

case 2: t1.pop(); break;case 3: t1.display(t1.root);break;case 4: exit(1);}

}}

1.INSERT2.POP 3.DISPLAY 4.EXITEnter your choice:1enter no of elements to insert: enter the elements75 24 36 11 44 2 211.INSERT2.POP 3.DISPLAY 4.EXITEnter your choice:32 5 11 21 24 36 44

1.INSERT 2.POP 3.DISPLAY 4.EXITEnter your choice22 11 21 24 36 44

1.INSERT 2.POP 3.DISPLAY 4.EXIT4.EXITEnter your choice:4

95

Page 96: Advanced c c++

Advanced C Programming

Optimal Binary Search Tree#include<iostream.h>#include<conio.h>#include<stdio.h>#define MAX 10int find(int i,int j);void print(int,int);int p[MAX],q[MAX],w[10][10],c[10][10],r[10][10],i,j,k,n,m;char idnt[7][10];

void main(){

clrscr();cout << "enter the no, of identifiers";cin >>n;cout <<"enter identifiers";for(i=1;i<=n;i++)gets(idnt[i]);cout <<"enter success propability for identifiers";for(i=1;i<=n;i++)

cin >>p[i];cout << "enter failure propability for identifiers";for(i=0;i<=n;i++)

cin >> q[i];for(i=0;i<=n;i++){

w[i][i]=q[i];c[i][i]=r[i][i]=0;w[i][i+1]=q[i]+q[i+1]+p[i+1];r[i][i+1]=i+1;c[i][i+1]=q[i]+q[i+1]+p[i+1];

}w[n][n]=q[n];r[n][n]=c[n][n]=0;for(m=2;m<=n;m++){

for(i=0;i<=n-m;i++){ j=i+m; w[i][j]=w[i][j-1]+p[j]+q[j]; k=find(i,j); r[i][j]=k; c[i][j]=w[i][j]+c[i][k-1]+c[k][j];}

}

96

Page 97: Advanced c c++

Advanced C Programming

cout <<"\n";

print(0,n);

}

int find(int i,int j){int min=2000,m,l;for(m=i+1;m<=j;m++)if(c[i][m-1]+c[m][j]<min){min=c[i][m-1]+c[m][j];l=m;}return l;}void print(int i,int j){if(i<j)puts(idnt[r[i][j]]);elsereturn;print(i,r[i][j]-1);print(r[i][j],j);}

OUTPUTenter the no, of identifiers4enter identifiersdoifintwhileenter success propability for identifiers3 3 1 1enter failure propability for identifiers2 3 1 1 1

tree in preorder formifdointwhile

97

Page 98: Advanced c c++

Advanced C Programming

Viva Voice Questions

1. What is the difference between an ARRAY and a LIST?

2. What is faster : access the element in an ARRAY or in a LIST?

3. Define a constructor - what it is and how it might be called (2 methods).

4. Describe PRIVATE, PROTECTED and PUBLIC - the differences and give examples.

5. What is a COPY CONSTRUCTOR and when is it called (this is a frequent question !)?

6. Explain term POLIMORPHISM and give an example using eg. SHAPE object: If I have

a base class SHAPE, how would I define DRAW methods for two objects CIRCLE and

SQUARE.

7. What is the word you will use when defining a function in base class to allow this

function to be a polimorphic function?

8. You have two pairs: new() and delete() and another pair : alloc() and free(). Explain

differences between eg. new() and malloc()

9. Difference between “C structure” and “C++ structure”.

10. Diffrence between a “assignment operator” and a “copy constructor”

11. What is the difference between “overloading” and “overridding”?

12. Explain the need for “Virtual Destructor”.

13. Can we have “Virtual Constructors”?

14. What are the different types of polymorphism?

15. What are Virtual Functions? How to implement virtual functions in “C”

16. What are the different types of Storage classes?

17. What is Namespace?

98

Page 99: Advanced c c++

Advanced C Programming

18. Difference between “vector” and “array”?

19. How to write a program such that it will delete itself after exectution?

20. Can we generate a C++ source code from the binary file?

21. What are inline functions?

22. What is “strstream” ?

23. Explain “passing by value”, “passing by pointer” and “passing by reference”

24. Have you heard of “mutable” keyword?

25. Is there something that I can do in C and not in C++?

26. What is the difference between “calloc” and “malloc”?

27. What will happen if I allocate memory using “new” and free it using “free” or allocate

sing “calloc” and free it using “delete”?

28. When shall I use Multiple Inheritance?

29. How to write Multithreaded applications using C++?

30. Write any small program that will compile in “C” but not in “C++”

31. What is Memory Alignment?

32. what is the difference between a tree and a graph?

33. How to insert an element in a binary search tree?

34. How to delete an element from a binary search tree?

35. How to search an element in a binary search tree?

36. what is the disadvantage in binary search tree?

37. what is ment by height balanced tree?

38. Give examples for height blanced tree?

39. What is a 2-3 tree?

99

Page 100: Advanced c c++

Advanced C Programming

40. what is a dictonary?

41.What is a binary search tree?

42. what is an AVL tree?

43. how height balancing is performed in AVL tree?

44. what is a Red Black tree?

45. what is difference between linked list and an array?

46. how dynamic memory allocation is performed in c++?

47. what are tree traversing techniques?

48. what are graph traversing techniques?

49. what is the technique in quick sort.?

50 what is the technique in merge sort?

51. what is data structure.

52. how to implement two stacks in an array?

53. what is ment by generic programming?

54. write the syntax for function templet?

55. write the syntax for class templet?

56. what is ment by stream?

57. what is the base class for all the streams?

58. how to create a file in c++?

59. how do you read a file in c++?

60. how do you write a file in c++?

Finite-State MachinesDerived from the on-line notes by Dr. Matt Stallmann & Suzanne Balik.

100

Page 101: Advanced c c++

Advanced C Programming

A finite-state machine (FSM) is an abstract model of a system (physical, biological, mechanical, electronic, or software).

An FSM consists of • States: a finite number of states that represent the internal "memory" of the system. • Inputs to the system (e.g., a user doing something, a character read from the input)• Transitions, which represent the "response" of the system to its environment.

Transitions depend upon the current state of the machine as well as the current input and often result in a change of state.

• An initial state, which is the state the system is in before it accepts any input.• Final states, states that represent a legal end to a transaction.

Simple example: A soda-pop machineConsider an FSM that models a soda-pop machine that dispenses soda-pop for 30 cents.The possible inputs to the machine are n - nickel, d - dime, q - quarter, s - select soda. The states of the machine are designated by circles.Each state is labeled with the amount of money that has been deposited so far.State 00 is the initial or start state. This is indicated by the incoming arrow. States which represent a total input of 30 or more cents are considered final states and are designated by double circles. The transitions from state to state are shown as arcs (lines with arrows). Each transition is labeled with the input that caused it.

Let’s take an example. Suppose the user inserts a sequence of coins … q takes the machine to state 25; another q takes it to state 50. It dispenses soda pop & change and transitions back to state 00.At this point, the user could select a drink.The machine would also have to give change.

101

Page 102: Advanced c c++

Advanced C Programming

An FSM for an ATMA finite-state machine can also be used to model a simple automated teller machine (ATM).In this case, each transition is labeled with an input—

• from the user (such as insert card), or • from a central database (such as PIN OK versus bad PIN).

Each of the transitions may, in actuality, involve a number of complex steps which are not shown on the diagram.

102

Page 103: Advanced c c++

Advanced C Programming

Recognizing input streamsFSMs can also be used to precisely define programming-language syntax. Another application of finite-state machines is as a notation for the precise description of a programming language syntax.Consider this description of real constants in Pascal: A real number in PASCAL is written as a string of digits containing a decimal point.There must be at least one digit before and after the decimal point.

103

Page 104: Advanced c c++

Advanced C Programming

Real data may also be represented using PASCAL scientific notation.A real data item written in scientific notation consists of a sign followed by a real number, followed by the letter E, another sign and an integer (+ signs may be omitted). The English description is imprecise. Are the strings .9 and 9. valid, or do you have to say 0.9 and 9.0, respectively? This FSM answers the question: A valid real constant in Pascal is any string that leads the FSM from the start state to a final (double-circled) state.

What happens when we feed the FSM .9? Starts out in State 0. There’s no transition for a dot, so that’s an illegal input.What happens when we feed it 9.? Starts out in State 0, and then goes to State 2 and then to State 3. But that’s an error, because State 3 is not an accepting state.What about the string 9.0? Starts out in State 0, and then goes to State 2 and then to State 3, and then Step 4. This is an accepting state, so 9.0 is a legal real constant.(Note that .9 and 9. are valid floating-point constants in Java.)

Text Processing with FSMsFinite-state machines are often used in text processing. The grep utility takes a string or regular expression and converts it to an FSM before doing a search.Simplifed example: Suppose a file consists of as and bs only and the search is for the string "abba". Here’s an FSM for doing this search:

If, for example, this FSM were used to locate the string "abba" in a file containing

"aababbbabba...", it would move through these states:

Input: a a b a b b b a b b a

104

Page 105: Advanced c c++

Advanced C Programming

State: 0 1 1 2 1 2 3 0 1 2 3 4The states listed above are the states of the machine after the corresponding input. When the final state 4 is reached, the search is successful.We say that the machine has recognized the string.

Exercise: Design an FSM that recognizes a string consisting of alternating as and bs, beginning with an a. If the input consists of anything else (e.g., abababaab, the FSM should continue to read it but not recognize it.Here is how an FSM can be developed and translated directly into a program.Consider the following specifications:

• A word is a maximal sequence of zero or more upper- and zero or more lower-case letters.Under this definition, what about the sequence "Go State!"?Is "State!" a word? No; it contains a punctuation mark.Is "tat" a word? No, because it is not maximal.How about "irregardless" Yes, because it’s a sequence of (0 or more) upper & lower-case letters.

• wc is the word count, initially 0 • lc is the line count, initially 0 • cc is the character count, initially 0

Here’s an FSM to recognize "words." Note that each transition is labeled with an action as well as an input.In state 0, the FSM remembers that we're not currently in the middle of a word, while state 1 remembers that we are.

Question: Why are there no final states in this FSM? It’s not trying to recognize anything; it’s just counting characters.An FSM’s behavior can also be specified by a table.Each row corresponds to a state Each column corresponds to an input symbol (or category of input symbols).The table version for the word counting FSM is given below.

105

Page 106: Advanced c c++

Advanced C Programming

State A–Z a–z \n other0 1: ++wc ++cc 0: ++lc, ++cc 0: ++cc1 1: ++cc 0: ++lc, ++cc 0: ++cc

A standard idiom for translating an FSM into a program is the while-switch idiom.• A while loop gets one character at a time from the input stream.• Inside the loop is a switch statement that causes different code to be executed based on the

current state. Here is the code.import java.io.*;public class WordCounter{

public static void main(String[] args) {if (args.length == 1) {

try {BufferedReader br = new BufferedReader(

new FileReader(args[0]));int wc = 0, lc = 0, cc = 0;char ch;int state = 0;int next;

while ((next = br.read()) != −1) {ch = (char) next;switch (state) {

case 0: if ( ch == ’\n’ ) {++lc;++cc;

}else if ( Character.isLetter(ch) ) {

state = 1;++wc;++cc;

}else

++cc;break;

case 1: if ( ch == ’\n’ ) {state = 0;++lc;++cc;

}else if ( Character.isLetter(ch) )

++cc;else {

106

Page 107: Advanced c c++

Advanced C Programming

state = 0;++cc;

}break;

default: System.out.println("Invalid state: " + state);

}}System.out.println( lc + "\t" + wc + "\t"+ cc);

}catch(IOException e) {

System.out.println("File error: " + e);System.out.println(

"usage: java WordCounter filename");}

}else

System.out.println("usage: java WordCounter filename");}

}Within each case, the program makes a decision based on the current input character.

Simplifying the programThe program can be simplifed by noting that—

• ++cc is done on every transition,• whenever the current input is \n we do ++lc and go to (or stay in) state 0, and• otherwise, the state and counters change only when

a letter is encountered in state 0 ora character other than a letter (or a newline) is encountered in state 1.

The simplified program looks like:

import java.io.*;public class WordCounter{

public static void main(String[] args) {if (args.length == 1) {

try {BufferedReader br = new BufferedReader(

new FileReader(args[0]));int wc = 0, lc = 0, cc = 0;char ch;int state = 0;int next;

while ((next = br.read()) != −1) {ch = (char) next;

107

Page 108: Advanced c c++

Advanced C Programming

++cc;if (ch == ‘\n’) {

++lc;state = 0;

}else if (state == 0 &&

Character.isLetter(ch)) {++wc;state = 1;

}else if (state == 1 &&

!Character.isLetter(ch)) {state = 0;

}}System.out.println( lc + "\t" + wc + "\t"+ cc);

}catch(IOException e) {

System.out.println("File error: " + e);System.out.println(

"usage: java WordCounter filename");}

}else

System.out.println("usage: java WordCounter filename");}

}

So FSMs can sometimes be "optimized" considerably.But, to avoid bugs, it is best to start with the straightforward implementation!

Summary1. Finite-state machines can be used to model the interaction between a system and its

environment. 2. The state of an FSM remembers what has occurred so far.

In addition to the FSM state, there may be variables that remember other details.The designer has to use judgment to decide what to model with an FSM state and what to leave as a variable.

3. A transition occurs when an event in the environment causes the system to change state (either the FSM state or variables).

4. A FSM can be depicted either by a bubble diagram or a transition table. 5. In text stream applications each transition corresponds to a single input character.

108

Page 109: Advanced c c++

Advanced C Programming

6. The while-switch idiom gives a method for mechanically translating a FSM to a program. Simplifications can be made by taking advantage of special features of the particular FSM.

Real Time Kernel

This is a project to implement a real-time kernel for the ARM processor. The main features of this kernel will be:

1) Priority based preemptive scheduling 2) Dynamic creation and deletion of tasks.3) Provision for all types of synchronization mechanisms.4) Mechanism for large number of timers.5) A simple best user API.

Prerequisites:

The following skills are essential for implementing this project.:

Operating System Concepts

A students must have a thorough understanding of Operating Systems concepts. In case the students don’t have this knowledge, a one week course on OS fundamentals must be conducted by the guide which must cover the following topics:

1) Scheduling2) Synchronization3) Mutual Exclusion4) I/O Management5) Process Management6) Memory Management

The discussion must be slanted towards Real-time systems. And implementation points must be discussed.

The following text books must used :

Operating System Concepts : Silbersatcz and GalvinOperating System : Design and Implementation : Tannenbaumm and Wood hull

C Programming in the Linux Environment

109

Page 110: Advanced c c++

Advanced C Programming

The students must have a very good knowledge of C programming language as it is the language for the project implementation. Further , the students must have moderate familiarity with the Linux application development process. The usage of GCC,MAKE and VI editor must be known by the students.

Compilation , Linking , Loading and Object Files Formats

A familiarity with object file formats and compilation process is essential.If the students don’t have any knowledge in this field , then a 1 day session ca be taken by the guide.

DESIGN OF THE KERNEL

The following are the steps for running a kernel(The detailed steps are given in the project schedule)

1) BOOTING 2) SYSTEM INITIALISATION

The steps are considered one by one :

BOOTING

Operating Systems are unlike other programs. It has to be put into memory by a separate program called boot-loader. It is because the kernel is the first program to run in the system.

There should be an understanding between the boot loader and operating system. The is given in a standard called multi boot. In Linux GRUB is the boot loader program which implements the multi boot standard. We have to understand this standard if we have to boot out own kernel.

The complete documentation of multi boot and GRUB is

1) Available on the Internet.

2) Available as online documentation on the Linux system[info grub].

SYSTEM INITIALIZATION

After booting the system has to be initialized. First the memory has to be initialized. Next the interrupts have to be setup. Finally if there is hardware to be initialized it is done.

In particular the Intel 80386 must be initialized as follows : (for the flat memory mode).

1) Disable all interrupts2) Setup GDT – kernel ‘s code, data, stack and other segments.

110

Page 111: Advanced c c++

Advanced C Programming

3) Setup IDT – manage all exceptions and interrupts.4) Load GDT register and IDT register.5) Initialize Hardware – setup timer hardware to generate periodic

interrupts.6) Enable Interrupts.

DATA STRUCTURES AND ALGORITHMS

The objective of this section is to give a high level view of the real-time kernel. All algorithms to implement the kernel are not described. Some of the core algorithms are described.

Usually in system’s software we have to design our data-structures first. The algorithms will naturally follow next(and will depend on the choice of the data structures)

As an example if we choose a matrix data structure our scheduling algorithm will be different than if we choose a multilevel ready queue based data structure.

Concepts :

An RTOS is a basic component of realtime embedded systems.It must provide mechanisms for

1) Multitasking – the ability to run more than one task at once.

2) Scheduling - the ability to make sure that timing criteria is met.

3) Synchronization – the ability to co-ordinate the activities of diverse tasks.

4) Memory management – to efficiently allocate memory for tasks and the kernel itself.

5) Interrupt and Timer Management : - handle interrupts and timersefficiently.

Block Diagram of a Real-time kernel

111

MEMORYMANAGEMENT

INTER – TASK COMMUNICATION MECHANISMS

USER TASKS

Page 112: Advanced c c++

Advanced C Programming

Functional Description of an RTOS

Tasks :

A task is basic unit of execution. A task is represented by an execution sequence and shares all resources with other tasks.The only resource that distinguishes one task from another is the stack used to store all the local variables.The system must know all information about the task to schedule it.This crucial information is stored in a structure called TCB.The TCB stores information about its stack in the SCB (stack control block). The SCB stores information about a stack – its base pointer, the size and other information. The TCB stores various information related to a task like id,priority.A task also needs to know the entry point – the function with the task has to begin executing.

These things are a minimum.There can be a lot more fields depending upon the complexity of the RTOS.

Scheduler : A scheduler is the heart of the operating system.Its main job is to make tasks run.That is it selects a task and dispatches it.Since there is usually one CPU , we need to do context switching between the tasks. Context switching – that is saving the context of one task and restoring anothers‘ s the basic activity – and this involves pushing and popping CPU registers. This is very much processor dependent and is usually coded in assembly.

Furthermore the scheduler must know at any instant of time all the tasks which are ready.Further more its has to know the highest priority task which is ready.For this it makes use of a multilevel queue – each queue holds tasks of particular priority.The scheduler chooses the task from the queue of the highest priority and schedules it.When the time period expires the task is preempted and the scheduler chooses the next ready task in the queue.

Tasks can also wait for resources(eg : char from keyboard).During this time the scheduler schedules another task which is ready.The task will become ready when an interrupt occurs.

Thus interrupts cause tasks to become ready.So the scheduler has to know is a higher priority task has become ready.If so it has to schedule it.Thus a mechanism is nessary for this.

Also interrupts can be nested.So the scheduler must run only when all interrupt have been handled.

112

HARDWARE

SCHEDULER + TASK MANAGEMENTI/O SYSTEM

Page 113: Advanced c c++

Advanced C Programming

SYNCHRONIZATION

Classical synchronization mechanisms like semaphores,mutexes,message queue must be implemented. All these mechanisms make use of a central mechanism called a wait queue. A wait queue is a queue on which tasks wait for some event to happen. A wait queue can be used to implement any synchronization mechanism. Thus a semaphore can implemented by a integer and a wait queue. All tasks on the queue are waiting for the semaphore resource. Like wise we can implement a message queue with a reader wait queue and a writer wait queue. Synchronization is related with scheduling.

And wait queues can be implemented as fifo ordered or priority ordered. This is important for real time kernels.A sample implementation of wait queues is provided by the Linux kernel.

Data structures and API for synchronization mechanisms are given below.

struct MsgQueue { // message queue data structure struct PQueue recvWait; struct PQueue sendWait;

}

struct MsgBuf { // message buffer

};

void MsgSend(struct MsgQueue *pMsgQ,struct MsgBuf *pMsg);struct MsgBuf *MsgRecv(struct MsgQueue *pMsgQ);unsigned int MsgCount(struct MsgQueue *pMsgQ);

struct Sem { // counting semaphore int value; struct PQueue semWait; };

struct Sem *SemCreate(void);void SemDelete(struct Sem *sem);

int AcquireSem(struct Sem *sem);void ReleaseSem(struct Sem *sem); int SemValue(struct Sem *sem);

struct BSem { // binary semaphore int state; struct PQueue bsemWait;

};

struct BSem * BSemCreate(void);void BSemDelete(struct Sem *sem);int AcquireBSem(struct BSem *bsem);void ReleaseBSem(struct BSem *bsem);

113

Page 114: Advanced c c++

Advanced C Programming

void BSemState(struct BSem *bsem);

struct Mutex { // mutex semaphore int state; struct Process *owner; unsigned int ldepth; struct PQueue mutexWait; };

struct Mutex* MutexCreate(void);void MutexDelete(struct Mutex *mutex);

int AcquireMutex(struct Mutex *mutex);void ReleaseMutex(struct Mutex *mutex);

struct Event { int occured; struct PQueue evWait; };int WaitEvent(struct Event *event);int SignalEvent(struct Event *event);int ResetEvent(struct Event *event);

Interrupt Handling API for the RTOS

Interrupts

Interrupts are the way external devices notify the application of an event. Interrupt service routines are the running entities executed to process an interrupt. Interrupt generation is very CPU dependent, but falls into two general categories.Several interrupt levels are usually offered by the CPU, each one generating a separate exception vector, handled by a separate interrupt handler. Interrupts may share interrupt levels or vectors, therefore the code in the interrupt service routine (ISR) must make sureit’s own device generated the interrupt before attempting to process it.

Some CPU architectures offer only one interrupt vector for all interrupt sources. In such a case, the hardware designer usually puts an interrupt controller chip between the devices and the CPU. It is up to the kernel implementor to write the general interrupt handler in such a way that it prioritizes the interrupts and dispatches the appropriate ISR.

Only a minimal amount of work to process the interrupt should be performed inside the ISR. A task should then be signaled, which in turn performs lengthy computations to complete the I/O operation. The only mutual exclusion mechanism available between ISRs are the interrupt disabling primitives The implementation of these functions are highly CPU

114

Page 115: Advanced c c++

Advanced C Programming

dependent. One some, interrupts are categorized among levels. On other’s, individual interrupt sources can/must be specified. Yet on others, it is only possible to disable all interrupts at once. In as much as possible, tasks and ISRs should only disable their own interrupts for mutual exclusion. All ISRs run at a higher priority than tasks. ISRs of the same priority are not time-sliced in a round-robin fashion. They run to completion unless interrupted by a higher priority interrupt. An ISR is restarted every time it is probable that it’s interrupt source generated the interrupt.

void IntAttach(int intNo,void (*intHandler)(int intNo,void devID,struct Regs *regs));int IntDetach(int intNo)(void);int IntEnable(int intNo);void IntDisable(int mask);void IntSetMask(int mask);int IntGetMask(void);

MEMORY MANAGEMENT

An RTOS does not use virtual memory for management of main memory. But tasks, stacks and other objects need memory. And so do user tasks to perform I/O. Thus a memory management scheme is needed to allocate and deallocate memory of fixed size and variable size. Various algorithms like first-fit , next-fit can be considered. But again we need to look into the real-time aspects of the algorithm – speed and determinacy.An extensive discussion of Kernel Memory Allocation is in [Vahalia].

One method of fast memory allocation is called caching : keep a queue of blocks of the same size. Allocate from the head of the queue. Deallocated blocks as added to the end of the queue.

For fixed size objects use this scheme : this allows use memory from other caches. For other things use a first-fit allocator. We can switch to other advanced memory allocation techniques.

In a RTOS we generally do not use virtual memory. Most memory is pre-allocated before the application starts and such preallocated blocks are called pools. The algorithm used to allocate memory from these pools may be first-fit or best-fit. Sometimes we may use cached buffers.

115

F F F FA

Page 116: Advanced c c++

Advanced C Programming

AAlklo Allocated Free

A easy way of memory allocation and deallocation is to use caches. The caches get their memory from a global memory area. The data structures and API is given below.

struct ObjHeader { void *next; char objp[1]; }; struct MemPool { unsigned int objsize; int maxobjs; int objcount; struct ObjHeader *headObj; };

void *MemAlloc(struct MemPool *mpool,int priority);void MemFree(struct MemPool *mpool,void *objp);

TASK IMPLEMENTATION

A task is represented within the kernel by a struct Task. It contains all the information necessary to define a task. In other systems it is called as a TCB(Task control block).

As an example consider :

struct Task { struct Task *next; // see below volatile int state; // see below int priority; // 0 – 31 int taskId; void *stack_base; void *stack_top; void *stackp; int (*task_entry)(void *arg); void *task_arg; };

In a real implementation it would contain more fields. A Task can be in any one of the following states :

#define READY 0#define RUNNING 1

116

Page 117: Advanced c c++

Advanced C Programming

#define WAITING 2#define FINISHED 4

There is support for 32 priority levels : #define NPRIOS 32

The state transition diagram from any OS – text book can be used as a reference.

All struct Tasks are stored in Hash-table which permits rapid searching of tasks given their task id.

The following data structures are used for the hash-table :

struct Task *task_table[]; // hash – table

An arrangement would look like the following :

task_table[] struct Task+--------+ +------+ +------+| |----->| |----->| |----| | | | | | | +--------+ +------+ +------+ | || | +--------+| | | . |

| . || . |+--------+| |------>+------+-----|| | | | | +--------+ | | +------+

A perfect size can be determined for the task table, so that given a taskid we can quickly lookup for the strict Task.

A task would look like the following :

struct Task+----------------+ | | +------>+------+ stack_base| | | | | | | | | | | |---------+ | | <-- stack area | |---------+ | | | | | | | | | +------>+------+ stack_top

117

Page 118: Advanced c c++

Advanced C Programming

| || | | |+----------------+

Scheduler Implementation

We need to support priority based preemptive scheduling. This means that it is guaranteed that the highest priority READY task will be running at anytime.The run queue is the main data structure used by the scheduler.It is an array of ready queues indexed by task priority – one for each priority.

Pictorially :

RunQueue+-------+| |---->+------+--->+-------+---|| | | Proc | | Proc | |+-------+ +------+ +-------+ -| || |+-------+| || |+-------+| || || || |+-------+| || |+-------+

The first queue will consist of all the tasks whose priority is equal to zero. The next slot will point to a queue which has tasks of priority 1 and so on. Only ready tasks will be on the queues. The queues will be circular which makes insertion and deletion fast.

The scheduler always selects the task on the first queue that is non empty and dispatches it. This ensures that the highest priority task will run first always.

After interrupts are handled , a higher priority task may have become ready. So the scheduler has to run so that the higher priority tasks will run.

There should be some way to know immediately which of the ready queue is non-empty. This is an implementation detail.

118

Page 119: Advanced c c++

Advanced C Programming

Sample Data structures and Algorithms

A queuing facility fundamental to an RTOS.Processes are queued and dequeued constantly to and from the run queues and wait queues.

A simple circular fifo queue is the best data structure for these operations.

struct PQElem { struct PQElem *next; struct Process *process;};

struct PQueue { Lock queueLock; int count; struct PQElem *lastElem;}; void InitQueue(struct PQueue *queue);void AddQueue (struct PQueue *queue,struct Process *process);struct Process *DelQueue(struct PQueue *queue);int GetCount (struct PQueue *queue);

#define NPRIOS 32 // number of priority levels we are supporting.struct PQueue RunQueue[NPRIOS]; // the ready queue is an array of

Timer Implementation

Timers are mechanisms which are like stop-watches. It allows a task to wait until a certain time period , call a function after a time period a implement a timeout period. There are many ways of implementing timers. They are discussed in [Varg].A simplified version will be given.The fundamental requirement is that we need a hardware clock which interrupts at regular intervals. This can be done on the PC using the 8254 timer. For more details see [Messmer]

volatile unsigned long jiffies; // incremented on every timer interruptstruct Timer { struct Timer *next; struct Timer *prev; int state; unsigned long expires; void (*timeout)(void *data); void *data;};

#define NTIMERS

unsigned long tcount;

struct Timer *timers[NTIMERS];

119

Page 120: Advanced c c++

Advanced C Programming

I/O Implementation

We are not providing a extensive mechanism for I/O like device drivers and file system. Unix-like operating systems provide I/O interface through the file –system. Since we are not providing a file-system we cannot use this interface. Another mechanism is needed.

The following I/O devices will be supported :

1) console and keyboard2) serial I/O3) timer and interrupt management.

Console in the IBM-PC is a memory mapped device. To do output we need to write to the video memory which is mapped at 0x8000.The details are in [Messmer].

The keyboard is a interrupt driven device. We need to convert the scan code and break code to a ASCII value (a simple scheme) , so that we can input ASCII data.

A simple terminal driver which processes (edits) character sequences can implemented on top of these drivers to provide standard input, output and error streams for Tasks. A shell can be implemented to test these drivers.

120