Last active
December 22, 2015 19:29
-
-
Save Embedded-linux/6520164 to your computer and use it in GitHub Desktop.
Stack program in C with array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /***Main Program **********/ | |
| #include <stdio.h> | |
| #define MAX 5 | |
| int status,top; | |
| int push(int stack[],int item) | |
| { | |
| if (top == MAX-1) | |
| { | |
| printf("Stack overflow \n"); | |
| status =0; | |
| } | |
| else | |
| { | |
| status = 1; | |
| ++top; | |
| stack[top] = item; | |
| } | |
| } | |
| /***Function to pop ***/ | |
| int pop(int stack[]) | |
| { | |
| int ret; | |
| if (top == -1) | |
| { | |
| status = 0 ; | |
| ret = 0; | |
| } | |
| else | |
| { | |
| status = 1; | |
| ret = stack[top]; | |
| --top; | |
| } | |
| return ret; | |
| } | |
| /***Function to Display *****/ | |
| void display(int stack[]) | |
| { | |
| int i; | |
| printf("The stack display is\n"); | |
| if (top == -1) | |
| { | |
| printf("Empty\n"); | |
| } | |
| else | |
| { | |
| for(i = top; i>=0; --i) | |
| printf("\n------\n|%3d |\n------",stack[i]); | |
| } | |
| printf("\n"); | |
| } | |
| void main() | |
| { | |
| int stack[MAX], item; | |
| int ch; | |
| top =-1; | |
| do | |
| { | |
| do | |
| { | |
| printf("Main menu\n"); | |
| printf("1.Push the item in the stack \n"); | |
| printf("2.Pop the item from stack \n"); | |
| printf("3.End of operation \n"); | |
| printf("Enter your choice \n"); | |
| scanf("%d",&ch); | |
| if (ch < 1 || ch > 3) | |
| printf("Invalid choice entry and please try again in between valid range \n"); | |
| }while(ch < 1 || ch > 3); | |
| switch(ch) | |
| { | |
| case 1: printf("Enter the item to be pushed\n"); | |
| scanf("%d",&item); | |
| printf("%d\n",item); | |
| push(stack,item); | |
| if (status) | |
| { | |
| printf("After pushing\n"); | |
| display(stack); | |
| if (top == (MAX-1)) | |
| printf("stack is full\n"); | |
| } | |
| else | |
| printf("stack overflow on push\n"); | |
| break; | |
| case 2: item = pop(stack); | |
| if(status) | |
| { | |
| printf("popped item is %d..after popping\n"); | |
| display(stack); | |
| } | |
| else | |
| printf("stack underflow on pop\n"); | |
| break; | |
| default: | |
| printf("End of execuation\n"); | |
| break; | |
| } | |
| } while(ch != 3); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment