You are on page 1of 13

Exploring Data Structures with C

DATA STRUCTURES D={d,F,A}


Where, D : Data structure d : Domain variable F : A set of functions or procedures operating on domain variables. A : A set of axioms or rules which governing the operations of these functions on the domain variable.

DATA STRUCTURES
Linear Data Structure Ex : Stacks, Queues, Linked Lists Non-linear Data Structure Ex : Trees, Graphs

DATA STRUCTURES
The logical inter-relation between elementary data items is called as data structure. The basic data items include integers, bits, characters. Basically it deals with manipulation and organization of data, solving problems with computer involves data manipulation. But the data available will usually be in amorphous form. When different types of such data are related to each other, then we call it to be a data structure. Ex : Queues, Trees, etc.

ADVANTAGES
The major advantages of data structures are :

It gives different level of organizing data. It tells how data can be stored and accessed in its elementary level.

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

OPERATION ON DATA STRUCTURES


The operations that can be performed on data structures are : Creation : This operation creates a data structure. The declaration statement causes space to be created for data upon entering at execution time. Destroy : This operation destroys the data structure and aids in the efficient use of memory. Selection : This operation is used to access data within a data structure. The form of selection depends on the type of data structure being accessed. Update : This operation changes or modifies the data in the data structure and it is an important property in selection operation.

NON-PRIMITIVE DATA STRUCTURES


Non-primitive data structures can be classified as :

Arrays : An array is an ordered set which consists of a fixed number of objects. No deletion or insertion operations are performed on arrays.

Lists

: A list on the other-hand is an ordered set consisting of a variable number of elements to which insertions and deletions can be made. The list is divided into two types : Stacks and Queues.

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

Files

: A file is typically a large list that is stored in the external memory of a computer. Ex : Magnetic disks, Floppies, etc.

STACKS
Lists permit the insertion or deletion of an element to occur only at one end. A linear list belonging to this subclass is called a stack. They are also referred to as pushdown lists. The insertion operation is referred to as PUSH and the deletion operation as POP. The most accessible element in a stack is known as the TOP of the stack. Since insertion and deletion operations are performed at one end of stack, the elements can only be removed in the opposite order from that in which they were added to the stack. Such a linear list is frequently referred to as a LIFO ( Last-In First-Out ) LIST.
IN TOP File 4 File 3 File 2 File 1 OUT ( Removed in the opposite order )

Fig : STACK ( Executive Tray ) An example of stack is the in tray of a busy executive. The files pile up in the tray and whenever the executive has time to clear the files, he/she takes it off from the top. That is, files are added at the top and removed from the top. Therefore stacks are sometimes referred to as LIFO structure.

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

A pointer TOP
A pointer TOP keeps track of the top element in the stack . Initially when the stack is empty, TOP has a value of 1 and when the stack contains a single element, TOP has a value of 0 ( Zero ) and so on. Each time a new element is inserted in the stack, the pointer is incremented by 1. The pointer decrements by 1 each time a deletion is made from the stack.

STACK STRUCTURE

D={d,F,A}
Where, d : Array or a node (structure) d = { a , TOP } Here, a : Simple array or structure TOP : Index or Pointer

F : PUSH, POP, DISPLAY, MODIFY A : EMPTY, OVERFLOW, UNDERFLOW

16 45 30 -1 TOP 0 TOP 30 PUSH OPERATION 1 TOP 45 30

TOP

45 30

TOP 30 0 TOP -1 TOP

POP OPERATION Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

ALGORITHM : STACK
Procedure PUSH(S,TOP,X) : This procedure inserts an element X to the top of the stack which is represented by a vector S consisting MAX elements with a pointer TOP denoting the top element in the stack. STEP 1 : [Check for stack underflow] If (TOP>=max-1) then write(stack overflow) Return STEP 2 : [Increment TOP] TOP TOP+1 STEP 3 : [Insert element] S[TOP] X STEP 4 : [Finished] Return The 1st step of this algorithm checks for an overflow condition.If such a condition exists,then the insertion can't be performed and an appropriate error message results.

Procedure POP(S,TOP,X) : This procedure removes top element from the stack. STEP 1 : [Check for the underflow on stack] If (TOP<0) then write(stack underflow) Return STEP 2 : [Hold the former top element of stack into X] X S[TOP]

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

STEP 3 : [Decrement the TOP pointer or index by 1] TOP TOP-1 STEP 4 : [finished-Return the popped item from the stack] Return(X) As Underflow condition is checked for in the first step of the algorithm. If such a condition exists, then the deletion cannot be performed and an appropriate error message results.

Procedure Display(S,TOP) : This procedure displays the contents of the stack i.e., vector S. STEP 1 : [check for empty on stack] if (TOP==-1) then write('stack empty') Return STEP 2 : [Repeat through STEP 3 from i=TOP to 0] Repeat through STEP 3 for i=TOP to 0 STEP-1] STEP 3 : [Display the stack content] write (S[i]) STEP 4 : [Finished] Return The first step of this algorithm checks for an empty condition. If such a condition exists, then the contents of the stack cannot be displayed and an appropriate error message results.

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

Write a C program to demonstrate the working of a stack of size N using an array. The elements of the stack may be assumed to be of type integer or real. The operations to be supported are: 1.PUSH 2.POP 3.DISPLAY. The program should print appropriate messages for stack overflow, stack underflow and stack empty. //c4sstack.c #include<stdio.h> #define MAX 5 int top,stack[MAX]; void init() { top=-1; } void push(int x) { stack[++top]=x; } int pop() { return(stack[top--]); } void display() { int i; printf("The stack content is:\n"); for(i=top;i>=0;i--) printf("%d\n",stack[i]); } int overflow() { if(top>=MAX-1) return 1; else return 0; } int underflow() { if(top<=-1) return 1; else return 0; } int empty() { if(top==-1) return 1; else return 0; }

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C main() {

int item,choice; clrscr(); init(); while(1) { printf("\nMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n"); printf("Enter your choice\n"); scanf("%d",&choice); switch(choice) { case 1: if(overflow()) printf("stack overflow\n"); else { printf("Enter an element to be inserted\n"); scanf("%d",&item); push(item); } break; case 2: if(underflow()) printf("stack underflow\n"); else printf("The deleted item is %d\n",pop()); break; case 3: if(empty()) printf("stack is empty\n"); else display(); break; case 4: exit(); default: printf("Invalid choice\n"); } } }

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

INFIX, POSTFIX AND PREFIX


Consider the sum of A and B. We think of applying the operator + to the operands A and B to write the sum as A+B. This particular representation is called Infix notation. There are two alternate notations for expressing the sum of A and B using the symbols A, B and +. These are +AB AB+ Prefix notation Postfix notation

The prefixes pre-, post- and in- refer to the relative position of the operator with respect to the two operands. In Prefix notation the operator precede the two operands, In Postfix notation the operator follows the two operands and In Infix notation the operator is between the two operands. The evaluation of the expression A + B * C, as written in standard infix notation, requires knowledge of which of the two operations, + or * , is to be performed first. In the case of + and *, we know that multiplication is to be done before addition (in the absence of paranthesis to the contrary). Thus A+B*C is interpreted as A + ( B * C ) unless otherwise specified. We say that multiplication takes precedence over addition. Suppose that we want to rewrite A + B * C in postfix. Applying the rules of precedence, we first convert the portion of the expression that is evaluated first, namely the multiplication. By doing this conversion in stages, we obtain : A+(B*C) A + ( BC* ) A ( BC* ) + ABC*+ Paranthesis for emphasis Convert the multiplication Convert the addition Postfix form

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

10

The only rules to remember during the conversion process are that operations with highest precedence are converted first and that after a portion of the expression has been converted to postfix, it is to be treated as a single operand. Consider the same example with the precedence of operators reversed by the deliberate insertion of paranthesis. (A+B)*C ( AB+ ) * C ( AB+ ) C * AB+C* Infix form Convert the addition Convert the multiplication Postfix form

In the above example the addition is converted before the multiplication because of the paranthesis. In going from ( A + B ) * C to ( AB+ ) * C, A and B are the operands and + is the operator. In going from ( AB+ ) * C to ( AB+ ) C *, ( AB+ ) and C are the operands and * is the operator. The rules for converting from infix to postfix are simple, providing that you know the order of precedence.

Usual Operators + * / $

Precedence LR LR LR LR RL

Binary operations Addition Subtraction Multiplication Division Exponentiation

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

11

Algorithm : Evaluation of a Postfix or Suffix expression


STEP 1 : Read the given postfix expression into a string called postfix. STEP 2 : Read one character at a time & perform the following operations : 1. If the read character is an operand, then convert it to float and push it onto the stack. 2. If the character is not an operand, then pop the operator from stack and assign to OP2. Similarly, pop one more operator from stack and assign to OP1. 3. Evaluate the result based on operator x. 4. Push the result (based on operator x) onto the stack. STEP 3 : Repeat STEP 2 till all characters are processed from the input string. STEP 4 : Return the result from this procedure or algorithm and display the result in main program.

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

12

Write a C program to evaluate a valid suffix or postfix expression using Stack. Assume that the suffix expression is read as a single line consisting of non-negative single digit operands and binary arithmetic operators. The arithmetic operators allowed are + (ADD), -(SUBTRACT), *(MULTIPLY) and /(DIVIDE). // pfixc4s.c #include<stdio.h> #include<math.h> #include<stdlib.h> int operand(x) { if (x>='0' && x<='9') return 1; else return 0; } float stack[30]; char postfix[30]; int top = -1; /* FUNCTION TO PUSH AN ITEM ONTO THE STACK */ void push(float x) { stack[++top] = x; } /* FUNCTION TO POP AN ELEMENT FROM TOP OF THE STACK */ float pop() { return (stack[top--]); } /* FUNCTION TO CALCULATE RESULT OF OPERATOR PASSED FROM PROCESS */ float eval(float x, float y, char opr) { switch(opr) { case '+': return (x + y); case '-': return (x - y); case '*': return (x * y); case '/': return (x / y); case '^': return (pow(x, y)); } } /* FUNCTION TO PROCESS THE POSTFIX EXPRESSION */ float process() { int i,x; //char x; float oprnd1,oprnd2,result; for (i=0; (x = postfix[i])!='\0'; i++)

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

Exploring Data Structures with C

13

{ if (operand(x)) /* TO GET THE EXACT DIGIT TO BE PROCESSED */ push((float)(x - '0')); else { oprnd2 = pop(); oprnd1 = pop(); result = eval(oprnd1,oprnd2,x); push(result); } } return result; } /* MAIN PROGRAM */ main() { clrscr(); printf("Enter a postfix expression :\n"); scanf("%[^\n]s",postfix); printf("The result of the given expression is: .3f\n",process()); }

Author : Nanda Kishor K N

Source : www.c4swimmers.esmartguy.com

You might also like