C Programming language

adplus-dvertising
Static Implementation of Stack (Using Array)
Previous Home Next

The implementation of the stack using array with various operations that can be applied on stacks is given as following.

The following is a code that shows how can we implement stacks while using arrays.

#include <stdio.h>
#include<conio.h>
#define<stdlib.h>
#define MAXSIZE 17
void push();
void pop();
void display();
int stck[MAXSIZE];
int top=-1;
void main()
{
int choice;
char ch;
clrscr();
printf("Program for various operations on stack using arrays");
do
{
 printf("\n1. PUSH");
 printf("\n2. POP");
 printf("\n3. Display");
 printf("Enter your choice :");
 scanf("%d",&choice);
 switch(choice)
{
     case 1: push();
         break;
     case 2: pop();
         break;
     case 3: display();
         break;
 default : printf("\nwrong choice made");
    }
printf("\ndo you want to continue y/n");
fflush(stdin);
scanf("%c",&ch);
}
while ((char=='y')||(char=='Y'));
getch();
}
void push()
{
int info;
if(top==MAXSIZE-1)
{
    printf("\nStack Overflow");
}
else
{
     printf("\nEnter the element you want to add to stack");
 scanf("\n%d", &info);
 top=top+1;                   /* increasing top to accommodate new element*/
 stck[top]=info;              /* placing the new element to the top */
    } }
void pop()
{
int info;
if(top==-1)
{
     printf("\n the stack is empty");
}
else
{
     info=stack[top];                        /*placing top element to info */
 top=top-1;                                  /*decreasing the top value */
 printf("\n the deleted item is %d", info); /* returning the deleted value*/
    }
}
void display()
{
 int i;
 if(top==-1)
 printf("\n stack is empty");
 else
{
     printf("\nthe stack is displayed as :")
 for(i=top;i>=0;i--)
{
     printf("%d",stck[i]);
}
    }
}
Previous Home Next