Coders Packet

C Program for Implementation of Stack using Array

By Srishti Dhaval Patkar

This is a C program that implements the stack operations using an ARRAY. The program includes stack operations like Push operation, Pop operation, Display and Quit option.

Implementation of STACK using ARRAY

This is a C program that implements the stack operations using an array.

The stack operations in the given program are:

1) Push:  To insert an element into the stack.

In a stack, a new element is always added from the top of the stack. 

Given below is the function used in the code for push operation. 

First, the top is incremented by 1 and then stack[top] is updated.

void push (int x)
{
  if(top==N-1)
  {
    printf("\nStack overflow\n");	
  }
  else
  {
    top++;
    stack[top]=x;
  }
}

 

2) Pop:  To delete an element from the stack.

In a stack, an element is always deleted from the top of the stack. 

Given below is the function used in the code for the pop operation. 

First, we check if the stack is empty. If not, we decrement top by 1.

void pop()
{
  int item;
  if(top==-1)
  {
    printf("\nStack underflow\n");
  }
  else
  {
    item=stack[top];
    printf("\nDeleted item is %d\n",item);	
    top--;
  }
}

 

3) Display:

To display the elements in the stack.

Given below is the function to display the elements of the stack.

void display()
{	
  if(top==-1)
  {
    printf("\nStack empty\n");
  }
  else
  {
    printf("\nThe stack is: ");
    for(int i=top;i>=0;i--)
    {
      printf("%d ",stack[i]);
    }
    printf("\n");
  }
}

 

Download Complete Code

Comments

No comments yet