0% found this document useful (0 votes)
18 views123 pages

M1 - Final To Host

Data structures are methods of storing and organizing data in computer memory, with applications in operating systems, database management, compiler design, and software development. They can be classified into primitive (e.g., int, float) and non-primitive structures (e.g., arrays, stacks, queues), with further distinctions between linear and non-linear types. Key concepts include dynamic memory allocation, pointers, and various data structures like arrays, stacks, queues, linked lists, trees, and graphs.

Uploaded by

sjivanashree18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views123 pages

M1 - Final To Host

Data structures are methods of storing and organizing data in computer memory, with applications in operating systems, database management, compiler design, and software development. They can be classified into primitive (e.g., int, float) and non-primitive structures (e.g., arrays, stacks, queues), with further distinctions between linear and non-linear types. Key concepts include dynamic memory allocation, pointers, and various data structures like arrays, stacks, queues, linked lists, trees, and graphs.

Uploaded by

sjivanashree18
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

INTRODUCTION TO DATA STRUCTURES

What is data structure? Mention its applications

Data Structure:

It can be defined as a method of storing and organizing


the data items in the computer’s memory.

Mainly deal with


✓Storing data in memory
✓Organizing data in memory
✓Fetching and processing data
Applications of dsc
1. Operating system
Queues are used for inter process communications
Stack is used when a function is called
Linked lists are used in dynamic memory management tasks

2. DBMS(Data base management system


B tree hashing indexing are used for faster data
access from disk

3 compiler design
stacks are used in pushing
compilers syntax check for matching braces .implemented by stack

4. Software development
Data Structures are…

Array
Stack
Queue
Linked List
Tree
Graph
File
Explain classification
of data structure
Or
Lists different types of
data structure with an ex
Primitive data structure
The data structures, that are directly operated
upon by machine level instructions i.e. the
fundamental data types such as

➢ int,
➢float,
➢ char
➢Pointer
Define non-premitive data
structure. Give example
A data structure that cannot be
manipulated directly by machine
instructions are called non-premitive data
structure .

ex: arrays, stacks, queues ,lists


Files, trees, graphs
Non-primitive data structure
There are two types of-non primitive data structures.
The non-primitive data types cannot be manipulated
by machine instructions.

Linear and Non-Linear Data Structures:


In a linear data structure, the data items are arranged in
a linear order or sequential. For Example: array,
Stack, lists,queue.

In a non-linear data structure, the data items that are


not in sequence. For Example: trees and graphs.
Definition:
An array is a sequence of data item of homogeneous
value(same type).

int aitm[5] 10 20 30 40 50

Arrays are of two types:

➢One-dimensional arrays

➢Multidimensional arrays
Array Elements
or
Items
Stacks
A stack is a linear data structure in which an element
may be inserted or deleted only at one end called the
top end of the stack

→last-in-first-out (LIFO)
Application of Stacks

➢Recursive functions
➢Reversing string
➢Evaluation of Expression
➢Conversions of expressions infix, postfix, prefix
➢Implementation of function calls
Queue
Queue is a linear data structure in which insertion can take
place at only one end called rear end and deletion can take
place at other end called front end.

The front and rear are two terms used to represent the two
ends of the list when it is implemented as queue.

Queue is also called First In First Out (FIFO)


Types of queues are
1. Queue (ordinary queue)
2. Circular queue
3. Double ended queue
4. Priority queue
Applications of Queues:
a)Number of print jobs waiting in a queue, when we
use network printer.

b) Call center phone system will use a queue to hold


people in line until a service representative is free.

c) Buffers on MP3 players and portable CD player,


iPod playlist are all implemented using the concept of
a queue.

d) Movie ticket counter system, it maintains a queue to


take tickets based on first come first serve
Linked list
A linked list is a data structure which is collection of
zero or more nodes with each node consisting of two
field’s data and link.

Data field consists the information of be processed.


Link field contains the address of the next node.

Types of linked list are


1. Singly Linked List
2. Doubly Linked List
3. Circular Singly Linked List
4. Circular Doubly Linked List
head

10 20 30 40

Data link
Trees
A tree is a nonlinear data structure and is
generally defined as a nonempty finite set of
elements, called nodes such that:
1. It contains a distinguished node called root of
the tree.
2. The remaining elements of tree is called child
nodes
A graph normally a combination of the set
of vertices V and set of edges E.
Difference between structure and union
struct keyword union keyword
unique memory location memory location is shared
Changing the value of one Changing the value of one
data member will not affect data member will affect
other data members other data members
we can retrieve any member we can retrieve only one
at a time member at a time
SELF-REFERENTIAL STRUCTURES

Self Referential structures are those structures that


have one or more pointers which point to the same
type of structure or itself, as their member.
It usually require dynamic storage management
routines ( malloc() and free() ) to explicitly obtain
and release memory.
Self Referential structures are those structures that have one
or more pointers which point to the same type of structure or
itself, as their member.

struct cse 3rdsem a 3rdsem b


{
int data1;
Data1 and Data2: variables
int data2;
struct cse * next;
next: it is a pointer to a
3rd sem a and
} 3rdsem a, 3rdsem b;
3rd sem b structure.
What is a pointer? How do you
declare and initialize the pointer?
How do you access the value
pointed to by a pointer.(6)
Definition:
It is a variable that stores or points the address of
another variable.
This variable can be of type int, char, array, function,
or any other pointer.
aitm
Declaring of a pointer variable
Syntaaitm:
data_type * pointer_name;
Ex :
int * aitm ;
(*) tells that the variable is a pointer variable.
*
Two operators:

&:the adress operator

*:the dereferencing operator


#include<stdio.h>
void main () aitm cse
{ 200
int cse=10; 10
int *aitm; 500 200
aitm=&cse;

printf("value of pointer is %d", *aitm); 10


printf(“value of x is %d",cse); 10

printf("address of pointer is %d",aitm); 200

printf("address of x is %d",&cse); 200

}
Define pointers. Give
advantages and
disadvantages of pointers
What are the Applications of pointer?
1)Allocate and access memory dynamically
2) Return more than one value from a function
3)Create and manipulate data structure such as linked
lists, trees,
4) Passing of arrays and strings from one function to
another with greater flexibility.
Disadvantages of pointers:-
Pointers are slower than normal
variables.
If pointers are updated with incorrect
values, it might lead to memory corruption.
we can access the restricted memory
area.
if sufficient memory is not available
during runtime for the storage of pointers,
the program may crash
Dynamic Memory allocation
Dynamic Memory allocation
Dynamic memory allocation is the process of
allocating memory during run time(execution time).
Additional storage can be allocated whenever
needed.
List and explain any 4 dynamic
memory functions with an
examples
To implementing dynamic memory the following 4
functions are used.
1.malloc( ):
2. calloc( ):
3. realloc( ):
4. free( ):
1. malloc( ):
Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
Syntax:
ptr=(datatype *)malloc(size);
where,
 ptr is a pointer variable of type datatype
 datatpe can be any of the basic datatype or user define datatype
 Size is number of bytes required.
Example:
int *p;
ptr=(int*)malloc(100*sizeof(int));
It will allocate either 200 or 400 bytes size of the int is either 2 or 4 bytes
The calloc Function
It stands for contiguous allocation. It is used to allocate
multiple blocks of memory.
It requires two parameters as number of elements and size
of each element.
Syntax:
ptr=(datatype *)calloc(n , sizeof(Datatype);
where,
ptr is a pointer variable of type datatype
datatype can be any of the basic datatype
n is number of blocks to be allocated
size is number of bytes required.
realloc()
It changes the size of block by deleting or
extending the memory at end of the block.
 If memory is not available it gives complete
new block.
Syntax:
ptr=(datatype *)realloc (ptr , sizeof(datatype);
where,
 ptr is a pointer to a block previously allocated memory
either using malloc() or calloc()
 Size is new size of the block.
free()
This function is used to de-allocate(or
free) the allocated block of memory
which is allocated by using functions
malloc(), calloc(), realloc().
Syntax:
free(ptr);
ARRAYS
Definition
An Array is defined as, an ordered set of similar data items. All
the data items of an array are stored in consecutive memory
locations.
Abstract Data Type:
Array create:
Item retrive:
Array store:
Declaration of one-dimensional array
data_type array_name [array_size] ;

For example: int aitm [5];

Here, the name of array is aitm


The size of an array is 5,i.e., there are 5
items(elements) .
All element in an array are of the same type (int, in
this case).
Example of array in C programming

C program print the number of elements using an arrays

#include<stdio.h>

void main() int a[5] 10 20 30 40 50


{
int aitm[10],i,n;
printf("Enter array size");
scanf("%d", &n);
Output :
printf("Enter array elements");
Enter an array size
for(i=0; i<n; i++)
5
{
scanf(“%d”, & aitm[i]); Enter an array elements
} 10
printf(“the array elements are "); 20
30
for(i=0; i<n; i++) 40
{ 50
printf(“%d” , aitm[i]);
The elements are
}
10 20 30 40 50
}
Two-dimensional Arrays
The simplest form of multidimensional array is the two-
dimensional array.
An array of arrays is known as 2D array.
It is also known as matrix.
A matrix can be represented as a table of rows and columns

Declaration of two-dimensional array is


Data type arrayName [ x ] [ y ];

int aitm [3] [4];


2D array can be represented in memory
using any of the following two ways:
1. Column-Major Order
2. Row-Major Order
1.Column-Major Order
In this method the elements are stored column wise, i.e. m elements of first column are
stored in first m locations, m elements of second column are stored in next m locations
and so on.
E.g.
A 3 x 4 array will stored as below:
2. Row-Major Order:
In this method the elements are stored row wise, i.e. n elements of first
row are stored in first n locations, n elements of second row are stored in
next n locations and so on. E.g.

A 3 x 4 array will stored as below


Given 25*4 matrix
Base is 200
W=4
Find address of 3rd test of 12th student ie
score(12,3) =?
Array of array
representation
Jagged array is array of arrays such that member
arrays can be of different sizes, i.e., we can create a 2-
D array but with a variable number of columns in each
row. These type of arrays are also known as Jagged
arrays.
Example:
arr[][] = { {0, 1, 2},
{6, 4},
{1, 7, 6, 8, 9},
{5}
};
Multidimensional Arrays

C programming language allows multidimensional


arrays.
Here is the general form of a multidimensional array
declaration −
Datatype name [size1] [size2] ... [sizeN];
For example, the following declaration creates a three
dimensional integer array −
int threeD[5][10][4];
What is dynamically
allocated arrays? Explain
with an example
Dynamically allocated arrays
A dynamic array is quite similar to a regular array, but its
program runtime .
size is modifiable during ____________________
Dynamic Array elements occupy a contiguous block of
memory.
dynamic memory allocation requires two steps:

Creating the dynamic space.

Storing its address in a pointer
Ex:-C pgm to read a 1D array and print array elements
using Dynamic Memory Allocation.

#include <stdio.h> for(i=0;i<n;i++)


#include<stdlib.h> {
void main() printf(“the elements are %d\n",*(p+i));
{ }
int i,n; }
int *p;
printf("enter the size\n");
scanf("%d",&n);
p=(int*)malloc(n*sizeof(int));
printf("enter the elements\n");
for(i=0;i<n;i++)
{
scanf("%d",(p+i));
}
Strings:
Character set: each programming
language contains a character set to
communicate with the computer.
Alphabets: a to z
Digits : 0 to 9
Special characters : + - / * = ‘ ‘ “ “
Strings
BASIC TERMINOLOGY
String can be defined as the one-dimensional array
of characters terminated by a null character '\0'.
The character array or the string is used to
manipulate text such as word or sentences
Each character in the array occupies one byte of
memory, and the last character must always be null
('\0')
String Operations:
Substring Finding part of the string is done
in substring
SUBSTRING(String, Initial, Length)
String- Name of string
Initial- Position of the first character
Length- Length of the substring
For ex: In string ‘Aitm cse div A’ we find
the substring ‘cse’ by using
SUBSTRING(‘Aitm cse div A’, 9,7)
SUBSTRING(String, Initial, Length)
Ex: In string ‘A I t m c s e D I V A’
1 2 345 6 7 89 10 1112 13
we find the substring ‘cse’ by using
SUBSTRING(‘Aitm cse div A’, 6,3)
cse
Indexing
Finding position where the pattern P first
appears in the string
INDEX(String, Pattern)
String- Name of string
Pattern – Pattern which we want to find If the
pattern does not found then INDEX is assigned
the value 0
For ex:
In string ‘A I TM CSE D I V A’ we find the
INDEX of ‘CSE’ by using
INDEX(‘A I TM CSE D I V A’ , ‘CSE’)
6
Concatenation
For string S1 & S2, finding new string
consisting of char of S1 followed by char of
S2.
Denoted by S1//S2
For ex: S1= ‘CSE’,
S2= ‘DIV A’ then
S1//S2 ‘CSE DIV A’
Length
The number of character in string is called
its length
Denoted by LENGTH(String)
For ex: LENGTH(‘aitmcse’)
7
String Functions
strcpy(s1, s2);
Copies string s2 into string s1.
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
strlen(s1);
Returns the length of string s1.
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1s2.
Write a c program to
i)reverse a string
ii)concatinate two strings
#include<stdio.h>
#include <string.h>
void main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
strcpy(str3, str1);
strcat( str1, str2);
len = strlen(str1); Hello
printf(“copied string is : %s", str3 );
printf(“concatenation of a string is %s", str1 ); Hello world
printf(“length of a string is : %d", len ); Lengnth is 10
}
ADT String is

String null
Integer compare(s,t)
Boolean isnull(s)
Integer Length(s)
String concat(s,t)
String Substr(s,I,j)
PATTERN MATCHING ALGORITHMS
Write knuth morris pratt pattern
matching algo and apply the same
to search the
pattern ‘abcdabcy’ in the
text ‘abcxabcdabxabcdabcdabcy’
Or write 2nd lab program
Knuth morris pratt pattern matching algorithm

Int pmatch(char *string, char *pat)


{
int i=0,j=0;
Int lenthstring=strlen(string);
Int lenpattern=strlen(pat);
while(i<lenthstring && j<lengthpattern)
{
if(string[i] == pat[j])
i++; j++;
}
else if ( j==0)
i++;
2 lab pgm
else
j=failure[j-1]+1;
}
Return ((j==lenthpattern) ? (i-lentghtpattern) : -1) ;
What is polynomial? What is
degree of the polynomial?
Write a function to add two
polynomials
POLYNOMIALS
“A polynomial is a sum of terms, where each term has a form
axe where
x is the variable,
a is the coefficient and
e is the exponent.”

Ex : 2
2x +3x+1
The largest (or leading) exponent of a
polynomial is called its degree.
Consider two polynomials show
pictorial representation in 1 d
array also give c representation
poly_pointer padd(poly_pointer a, poly_pointer b)
{
poly_pointer c, rear, temp;
int sum;
function to add
rear =(poly_pointer)malloc(sizeof(poly_node));
front = rear;
two polynomials
while (a && b)
{
switch (COMPARE(a->expon, b->expon))
{
case -1: /* a->expo n < b->exp on */
attach( b->coef, b -> expon, &r ear);
b= b->link; br eak;
case 0: / * a->exp on == b->expon */
sum = a ->coef + b-> coef;
if (sum) att a c h (sum ,a->expon,&rear);
a = a->link; b = b->link; break;
case 1: /* a->expon > b->expon */
atta ch(a->coef, a->expon, &rear);
a = a->link;
}
Give ADT of sparse matrix and show
with suitable example sparse matrix
representation storing as triplets give
sample transpose functions
SPARSE MATRICES
Sparse matrix is a special matrix made of
m rows and n columns, therefore having
total m x n values with most of its elements
are zero.
We can also assume that if (m * n) / 2
elements are zero then it is a sparse matrix.
ADT SparseMatrix
A set of triples, <row, col, value>,
functions
void create(n): creates a SparseMatrix
SparseMatrix transpose(A)
SparseMatrix add(A,B):
SparseMatrix multiply(A,B)
ADT SparseMatrix
A set of triples, <row, col, value>,
functions
void create(n): creates a SparseMatrix that can hold n non-zero elements
information.

SparseMatrix transpose(A): return the matrix produced by


interchanging the row and column value of every triple.

SparseMatrix add(A,B): if dimensions of a and b are the same return


the matrix produced by corresponding items, namely those with
identical row and column values else return error.

SparseMatrix multiply(A,B): if number of columns in a equals number


of rows in B return the matrix D produced by multiplying A by B
according to the formula: D[i][j]=
Ʃ(A[i][k]*B[k][j]) where D[i][j] is the (i,j) thelement else return error.
(m * n) / 2
Express the given sparse
matrix as triplets and find
its transpose
With example illustrate that
product of 2 sparse matrices may
not be sparse
Write c function for matrix
multiplication of 2 sparse matrix
Inserting an elements in a stack

C
B B
A A A

deleting elements in a stack


C
B B
A A A
Stack Standard operations:
IsEmpty : return true iff stack is empty

IsFull : return true iff stack has no remaining


capacity

Top : return top element of stack

Push: add an element to the top of the stack

Pop :delete the top element of the stack


Stack CreateS(maxStackSize) ::=

#define MAX_STACK_SIZE 100 /* maximum


stack size */
typedef struct
{
int key;
} element;

Element stack[MAX_SSTACK_SIZE];
Int top = -1;

Boolean IsEmpty(stack) ::= top<0;

Boolean IsFull(Stack) ::= top >=


MAX_STACK_SIZE – 1;
Define stack and write the
ADT(Abstract Data Type) of
stack implement push pop
functions for stack using with
stack full and stack empty
conditions(8)
Abstract data type Stack
ADT Stack is
Object: a finite ordered list with 0 / more elements.

Functions: for all stack belongs to Stack, item belongs to element,


maxStackSize belongs positive integer.

Return type function name


Stack Create(StackSize)::= create an empty stack whose
maximum size is StackSize
Abstract data type Stack
Return type function name
Boolean IsFull(stack ,StackSize)::=

if number of elements in stack equals to Stack _Size return TRUE else


return FALSE

Stack Push(stack, item) ::= if (IsFull(stack)) stack is Full


else insert item into top of stack and return.
Abstract data type Stack
Return type function name

Boolean IsEmpty(stack) ::=if no elements are there in stack return


TRUE else return FALSE

Element Pop(stack) ::=if (IsEmpty(stack)) return


else remove and return the element at the top of
the stack
Array representation of stacks
Stacks may be represented in the computer by one-way list
or a linear array.
Pointer variable TOP, which contains the location of the top
element of the stack.
And variable maxStacksize gives the maximum number of
elements that can be held by stack

The condition top =0 or top =null will indicate that stack is


empty.
MAXSTK = 8,
TOP = 3,
the stack has 3
elements,
XXX, YYY and
ZZZ;
Linked List Representation of Stacks :

Array representation of stacks is very easy and


convenient but it allows the representation of only
fixed sized stacks.

In several applications, the size of the stack may vary


during program execution.

An obvious solution to this problem is to represent a


stack using a linked list.
Linked List Representation of Stacks :
A single linked list structure is sufficient to represent any stack.

Here, the DATA field is for the ITEM, and the LINK field is, as usual,
to point to the next' item.

DATA
Write the algorithm to implement a
stack using dynamic array whose initial
capacity is 1 and array doubling is used
to increase the stack’s capacity(ie
dynamically reallocate twice the
memory) whenever an element is added
to full stack. Implement the operations
push pop and display (8)
Stack using Dynamic Arrays
Concept
whenever the inside of the stack is full, the memory is
expanded by dynamic allocation of the realloc
function.

Use a variable called capacity in place of


MAX_STACK_SIZE
Initialize this variable to (say) 1
When stack is full, double the capacity using
REALLOC
This is called array doubling
stack CreateS()

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
int key;
} element;

element *stack = (element *)malloc(sizeof(*stack));


int capacity = 1;
int top = -1;

Boolean IsEmpty(stack) ::= top < 0;


Boolean IsFull(stack) ::= top >= capacity-1;
StackFull()

void StackFull()
{
REALLOC(stack, 2*capacity*sizeof(*stack);
capacity *= 2;
}

Increase by 2 times with


2*capacity*sizeof(*stack) with realloc.
-And since the memory has been expanded, the capacity is
also doubled.
Complexity Of Array Doubling

Let final value of capacity be 2 k


Number of pushes is at least 2k-1+ 1
Total time spent on array doubling is S1<=i=k2i
This is O(2k)
So, although the time for an individual push is O(capacity), the time for all n
pushes remains O(n)!
Stack applications
Expression Evaluation
Stack is used by compilers to check for balancing of
parentheses, brackets and braces Function Call

Expression Conversion(infix to postfix, and prefix )

Implementation of recursive procedures:


all intermediate arguments and return values are stored
on the processor’s stack

During a function call the return address and arguments are


pushed onto a stack and on return they are popped off.

String Reversal
 Stack Applications:
-Polish notation,
-Infix to postfix conversion,
-Evaluation of postfix expression.
Polish notation
Polish Notation is a way of expressing
arithmetic expressions that avoids the use of
brackets to define priorities for evaluation of
operators

Example:
Infix notation with parenthesis: (a +b)

Polish postfix notation: ab+


A+B (A+B)*(C-D)

operator : + +, *, -
operands : A,B A,B,C,D
Types of expressions
Infix expression
Prefix expression
Postfix expression
Types of expressions
 Infix expression: the operator is place
in between 2 operands
(A+B) * (C-D)
 Prefix: the operator is place before the
operands
+AB
 Postfix: the operator is place after its
operands
A B+
Convert the infix to postfix
((a/(b-c+d))*(e-a)*c) .
Write the postfix form of the following.
((6+(3-2)*4)!^5+7) (4)
A$b$c*D (4)
(a+b)*d+e/(f+a*d)+c
((a/(b-c+d))*(e-a)*c)

write a function to evaluate that postfix


expression and trace for the given data
a=6,b=3,c=1,d=2,e=4.
Conversion of Infix expression to postfix expression

Postfix Expression
It follows the scheme of
<operand> <operand> <operator>
E.g. AB+
To make evaluation of an expression we should follow
the operator precedence table.

($ or ↑ or ^) Priority is 4

/ * Priority is 3

+– Priority is 2
# Priority is 1
Note:
$/ ^  represents exponentiation
23
Ex : 2$3$2 :  2 =512

3 2 =9

2 9 =512
1 Draw the table along with these headings characters,
stack and Result.
characters stack result

2 Write down the all characters in a table


Ex : (a + b)
Characters stack Result.
(
a Please refer class video to
+ understand these concepts
b
)
Algorithm for infix to postfix conversion
1.If the character is an operand, add it to the postfix result.

2 If the character is an operator. Then push it to the stack

3check the operator’s precedence and it is greater than or equal to the


precedence of the operator then push to the stack.

4.If the operator’s precedence is less than the precedence of the operator
then “pop out an operator from the stack and add it to the postfix result

3. If the character is “(“, then push it onto the operator stack.

4. If the character is “)”, then “pop out an operator from the stack and
add it to the postfix result.
Examples :->

1) A+(B*C-(D/E^F)*G)*H
2) ((A/B(B-C+D))*(E-A)*C
3) A/B-C+D*E-A*C
4) A*B/C
5) 2+3*4
6) A*B+5
7) ((((A/B)-C)+(D*E))-A*C))
8) A*(B+C)*D
9) A*B*C
10)A+B-C+D
11)A*-B+C
12)(A+B)*D+E/(F+A*D)+C
Evaluation of postfix expression.
Scan the postfix expression from left to right.
If the scanned symbol is an operand, then push it
onto the stack.

If the scanned symbol is an operator, then pop out two


symbols from the stack and assign to

A  Top element
B  Next to top element
Make operation
B (operator) A
<B> <operator> <A> respectively. Perform operation and
push onto stack

Repeat steps 2 and 3 till the end of the expression.


Ex:
4 5 +
If the scanned symbol is an operator, then
pop out two symbols from the stack
<B> <operator> <A>
and assign to
=9
9
A  Top element +
B  Next to top element
Make operation 5
A
B (operator) A
<B> <operator> <A> respectively. Perform
operation and push onto stack
B 4
Repeat steps 2 and 3 till the end of the expression.
Evaluation of postfix expression.
Ex: 4 5 6 + 2 - *

Ans : 36

A
B
Ex2 : 

10 2 8 * + 3 -

Ans 23
FUNCTION to evaluate postfix expression (4 times asked )

int eval(void)
{ Switch(token)
precedence token; {
Char symbol; case + : push(op1+op2); break;
int op1, op2; case - : push(op1-op2); break;
int n=0; case * : push(op1*op2); break;
int top=-1; case / : push(op1/op2); break;
token =gettoken(&symbol,&n); Case % : push(op1%op2); break;
While(token!=eos) }
{ }
if(token == operand) Token=gettoken(&symbol,&n);
push(symbol) }
else Return pop();
{ }
op2=pop();
op1=pop();
Recursion –

Tower of Hanoi
Tower of Hanoi
Tower of Hanoi, is a mathematical puzzle which
consists of three towers and more than one disks
is as follows −
These disks are of different sizes and stacked upon in
an ascending order, i.e. the smaller one sits over the
larger one.
Rules
The mission is to move all the disks to some another
tower without violating the sequence of arrangement.
Only one disk can be moved among the towers at
any given time.
Only the "top" disk can be removed.
No large disk can sit over a small disk.
Steps :--

aim is to move disk n from source to destination and


then put all other (n1) disks onto it. We can imagine to
apply the same in a recursive way for all given set of
disks.

The steps to follow are −


Step 1 − Move n-1 disks from source to temp
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from temp to dest
Write the algorithm for tower of Hanio(4)
Procedure : TOWER(N, BEG, AUX, END)
This procedure gives a recursive solution to the Towers of
Hanoi problem for N disks.
1. If N = 1, then:
(a) Write: BEG → END.
(b) Return.
[End of If structure.]
2. [Move N – 1 disks from peg BEG(src) to peg AUX(tmp).]
Call TOWER(N – 1, BEG, END, AUX).
3. Write: BEG → END.
4. [Move N – 1 disks from peg AUX to peg END.]
Call TOWER(N – 1, AUX, BEG, END).
5. Return.
What is recursion?
Write a c program to implement
tower of hanoi problem(8)
#include <stdio.h>
int count=0;
void towerhonai(int n, char src, char dst, char tmp)
{
count++;
if (n == 1)
{
printf(" Move disk 1 from rod %c to rod %c\n", src, dst);
}
towerhonai(n-1, src, tmp, dst);
printf("Move disk %d from rod %c to rod %c\n", n, src, dst);
towerhonai(n-1, tmp, dst, src);
}

void main()
{
int n;
printf("enter number of disks\n");
scanf("%d",&n);
towerhonai(n, 'A', 'C', 'B');
printf("Number of Moves Taken =%d\n",count);

You might also like