FoodForFutureGeeks

Thursday 3 January 2013

Stack Implementation using arrays with Menu for various operations.


This Program gives stack implementation using arrays, max stack size input 
is considered as 100 during implementation, modify it suitably.

#include<stdio.h>
#include<conio.h>

//Max stack size can be 99
//function declaration
void push(int* top,int* stackarray,int size, int ele);
void pop(int *top,int* stackarray);
void display_stack(int stackarray[],int top);


//main function
void main()
{
  int stackarr[100];
  int top          =-1;
  int size         =0;
  int ele          =0;
  int ch           =0;




  printf("enter the stack size less than 100\n");
  scanf("%d",&amp;size);


  //this menu will be displayed till user chooses to exit
    while(1)
   {
      printf("***************stackOperationsMenu*****************\n");
      printf("1--------->push an element int stack\n");
      printf("2--------->pop an element into stack\n");
      printf("3--------->display stack contents\n");
      printf("otherNum------>exit the program\n");
      printf("Enter your choice\n");
      scanf("%d", &ch);
      switch(ch)
      {
      case 1:printf("Enter the element to be pushed to stack\n");
             scanf("%d", &ele);
             push( &top,stackarr,size,ele);
             break;
      case 2:pop( &top,stackarr);
             break;
      case 3: display_stack(stackarr,top);
              break;


      default:return;
      }//end of switch
   }//end of while


  }// end of main


//function definitions
void push(int* top,int* stackarray,int size, int ele)
{
    if(*top  == size-1)
    {

        printf("stack is full\nPlease pop some elements and try to insert again\n");
    }
    else
    {  *top=*top+1;
        stackarray[*top]=ele;
    }
}
void pop(int* top,int* stackarray)
{
    if(*top == -1)
        printf(" stack is empty no element to pop\n");
    else
    {
        printf("Popped element is %d",stackarray[*top--]);
    }
}
void display_stack(int stackarray[],int top)
{
    int i=0;
    printf("Stack contents:\n");
    for(int i=0;i&amp;lt;=top;i++)
    {
        printf("%d\n",stackarray[i]);
    
} 

No comments:

Post a Comment