Saturday, October 8, 2016

C program to implement Stack using array.



#include<stdio.h>
void push();
void pop();
void display_stack();
int stack_pointer=0, stack[10];

int main()
{
  int n;
  do{
      printf("===== Stack Operation =====\n");
      printf("1. Push\n2. Pop\n3. Display Stack\n4. Exit\n");
      printf("Enter your choice:");
      scanf("%d", &n);
      switch(n){
        case 1: push();
                if(stack_pointer>=10)
                {
                  printf("Stack is full.\n");
                  exit(0);
                }
                break;
        case 2: pop();
                break;
        case 3: display_stack();
                break;
        case 4: printf("Thank you. Have a nice time..");
                break;
        default:
                printf("Select proper menu item.\n");
        }
  }while(n != 4);
  return 0; 
}
void push(){
   printf("\nPush Operation\n");
   printf("--------------\n");
   printf("Enter number to be pushed:");
   scanf("%d", &stack[stack_pointer++]);
   printf("Push Operation performed.\n");
   printf("-------------------------\n\n");
}
void pop(){
   printf("\nPop Operation performed.\n");
   printf("------------------------\n");
   printf("Popped out element from stack is %d\n\n", stack[stack_pointer-1]);
   stack_pointer--;
   getch();//developed by kp
}
void display_stack(){
   int i;
   if(stack_pointer==0)
       printf("Stack is empty.\n\n");
   else
   {
       printf("\nStack Elements are as under:\n");
       printf("----------------------------\n");
       for(i=0; i<stack_pointer; i++)
       {
           printf("%d\n", stack[i]);
       }
   }
   printf("\nPress any key to continue...\n\n");
   getch();//cprogrampracticals.blogspot.in
}


Output of the program:

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:1

Push Operation
--------------
Enter number to be pushed:5
Push Operation performed.
-------------------------

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:1

Push Operation
--------------
Enter number to be pushed:10
Push Operation performed.
-------------------------

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:3

Stack Elements are as under:
----------------------------
5
10

Press any key to continue...

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:2

Pop Operation performed.
------------------------
Popped out element from stack is 10

===== Stack Operation =====
1. Push
2. Pop
3. Display Stack
4. Exit
Enter your choice:4
Thank you. Have a nice time..

No comments:

Post a Comment