Flipkart.com

Monday, 30 April 2012

C Program to construct a stack of integers

//---------------------------------------//
//     C Program to Constract Stack      //
//        Coded by: Subham Nandi         //
//---------------------------------------//

#include<stdio.h>
#include<stdlib.h>
#define MAXSTK 10
int top=-1, stack[MAXSTK];
void push(int);
void display();
void pop();
int isempty();
int isfull();
int main()
{ 
 int item,choice;
 while(1)
 {
 printf("\nStack Operations");
 printf("\n1. Push");
 printf("\n2. Display");
 printf("\n3. Pop");
 printf("\n4. Exit");
 printf("\nEnter your choice:");
 scanf("%d",&choice);
 switch(choice)
 {
  case 1: printf("\nEnter the elements to be added:");
  scanf("%d",&item);
  push(item);
  break;
  case 2: printf("\nElements in the stack:");
  display();
  break;
  case 3: pop();
  break;
  case 4: exit(0);
  default:printf("\nError in choice");
  }
 }
}
void push(int item)
{
 if(isfull())
 {
  printf("\nStack Overflow\n");
  
 }
 else
 {
  top++;
  stack[top]=item;
  if(top==MAXSTK-1)
  printf("\nstack is full");
 }
 
}
void display()
{
 int p;
 p=top;
 printf("\nStack elements\n");
 if(p==(-1))
 {
  printf("\nStack is empty");  
 }
 else
 {
  while(p!=(-1))
  {
  printf("\n%d",stack[p]);
  p--;
  }
  
 }
}
void pop()
{
 int item;
 if(isempty())
 {
 printf("\nStack Underflow\n");
 }
 else
 {
 item=stack[top];
 top--;
 printf("\nThe popped element is %d",item);
 if(top==-1)
 printf("\nstack is empty");
 }
}
int isempty()
{
 if(top == -1)
  return 1;
 else
  return 0;
}
int isfull()
{
 if(top==MAXSTK-1)
  return 1;
 else
  return 0;
}

If you like the post please do suscribe us and like us on Facebook, also follow us on twitter.

0 comments:

Post a Comment

IHT