About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Monday, September 2, 2013

C Program to Implement Stack Operations Using Array

Program for implementing a stack using arrays.It involves
various operations such as push,pop,stack empty,stack full and
display.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5
/* stack structure*/
struct stack  {
          int s[size];
          int top;
           }st;
//-------------------------------------
int stfull()
{
 if(st.top>=size-1)
    return 1;
 else
    return 0;
}
//-------------------------------------
void push(int item)
{
 st.top++;
 st.s[st.top] =item;
}
//-------------------------------------
int stempty()
{
 if(st.top==-1)
    return 1;
 else
    return 0;
}
//-------------------------------------
int pop()
 {
 int item;
 item=st.s[st.top];
 st.top--;
 return(item);
 }
//-------------------------------------
void display()
{
 int i;
 if(stempty())
    printf("n Stack Is Empty!");
 else
  {
  for(i=st.top;i>=0;i--)
     printf("n%d",st.s[i]);
  }
}
//-------------------------------------
void main(void)
{
int item,choice;
char ans;
st.top=-1;
clrscr();
printf("ntt Implementation Of Stack");
do
{
 printf("n Main Menu");
 printf("n1.Pushn2.Popn3.Displayn4.exit");
 printf("n Enter Your Choice");
 scanf("%d",&choice);
 switch(choice)
 {
  case 1:
        printf("n Enter The item to be pushed");
        scanf("%d",&item);
        if(stfull())
            printf("n Stack is Full!");
        else
            push(item);
        break;
  case 2:
        if(stempty())
            printf("n Empty stack!Underflow !!");
        else
          {
          item=pop();
          printf("n The popped element is %d",item);
          }
        break;
  case 3:
        display();
        break;
  case 4:
        exit(0);
 }
 printf("n Do You want To Continue?");
 ans=getche();
}while(ans =='Y'||ans =='y');
getch();
}

Explanation of the C Porgram : Stack Using Array

Step 1 : Declare One Stack Structure

#define size 5

struct stack
{
     int s[size];
     int top;
}st;
  1. We have created ‘stack’ structure.
  2. We have array of elements having size ‘size’
  3. To keep track of Topmost element we have declared top as structure member.

Step 2 : Push/Pop Operation

While pushing remember one thing in mind that we are incrementing the top and then adding element. and while removing or poping the element, we are firstly removing the element and then decrementing the top.
void push(int item) {
    st.top++;
    st.s[st.top] =item;
}

No comments: