Stack using array Program blueprint

Declare array to implement stack:
int stk[MAX];                  | MAX is the size of the stackDeclare and Initialize top:
int top = -1;     
Stack should initially be empty and if  the value of top is -1, it means stack is empty.

We need to create 3 functions:

void push()                   – for inserting element into the stack
int pop()                        – for deleting element from the stack
void display()              – to display elements of the stack

Pushing element into the stack:
First check for stack overflow because in case the stack is full then we will not be able to insert any elements into the stack.

 

void push()
{

if(top == MAX - 1}
{
printf("Stack Overflow");
return;

/*** with the help of  return statement program control will come out of the push function .
If the condition (top == MAX-1 becomes true then 
we should come out of the push function ****/

}

top = top + 1;
stk[top] = element;

If the stack is full then stack overflow will be printed
If the stack is not full then the condition if(top == MAX – 1) will become false and the following two statements will get executed.
top = top + 1;

stk[top] = element; 
Here element is the value inputted by the user using scanf(); function, this value will be pushed into the stack.
 

Popping  element from the stack:
First you need to check for underflow condition because if the stack is empty or if the stack contains no elements then we cannot delete anything.

 

int pop()
{
int element;

*if value of top is -1 it means stack is empty*/
if(top == -1) 
{                                              
printf("Stack is empty");
return;
}

element = stk[top];  
top = top - 1;    /**** decrement the value of top by 1 ***/
return element;       
}

if(top == -1)  If the stack is empty then this condition will become true and if this condition becomes true then stack is empty will be printed and because of that return statement the pop function will terminate.
If the stack is not empty then the condition if(top == -1) will be false and the following three statements will get executed.
element = stk[top];
top = top – 1;
printf(%d  has been deleted”, element);
return element;

element = stk[top];
In a stack element is always deleted from the top so  stk[top]  will be the element to be deleted and by writing  element = stk[top];
we are assigning element the value that will be deleted from the stack.

printf(%d  has been deleted”, element);  will print the number which has been deleted from the stack.

Previous Post
Stack using array
Next Post
C Program to implement stack using array

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

alert('dsf'); console.log("dsdsdsd");