Exercise 3
Implement stack operations using pointers
Program::
#include< stdio.h>//Standard i/p,o/p header file #define max 100int arr[max],top=-1;int *stack=arr;/*Inserting the elements using push function*/ void push(int ele) { *stack=ele; printf("\n\nElement %d is pushed......\n\n",ele); stack++; top++; }/*Removing the elements using pop function*/ void pop() {if (top==-1) { print f("\n\nStack is empty....."); }else { printf("\n\nPoped element : %d",*(stack-1)); stack--; top--; } }/*Displaying the elements */ void display() {int t;if (top==-1) printf("\n\nStack is empty.....");else { printf("\n\nStack elements are : ");for (t=top;t>=0;t--) { printf("%d ",*(stack-(t+1))); } } }int main() {int num1=0,num2=0,i,ch; while(1) { printf("\n\t\tMENU "); printf("\n[1]Push Function\n[2] Pop Function\n[3] Elements present in Stack\n[4] Exit\n"); printf("\n\tEnter your choice: "); scanf("%d",&ch); switch(ch) {case 1: printf("\n\tEnter the element to be pushed:"); scanf("%d",&num1); push(num1);break; ;case 2: pop();break; ;case 3: display();break; ;case 4:break; ; default: printf("\nYour choice is invalid.\n");break; ; } } }
output::
gccpointers .c -opointers ./pointers MENU [1]Push Function [2] Pop Function [3] Elements present in Stack [4] Exit Enter your choice: 1 Enter the element to be pushed:8 Element 8 is pushed......MENU [1]Push Function [2] Pop Function [3] Elements present in Stack [4] Exit Enter your choice: 1 Enter the element to be pushed:2 Element 2 is pushed......MENU [1]Push Function [2] Pop Function [3] Elements present in Stack [4] Exit Enter your choice: 1 Enter the element to be pushed:17 Element 17 is pushed......MENU [1]Push Function [2] Pop Function [3] Elements present in Stack [4] Exit Enter your choice: 3 Stack elements are : 8 2 17MENU [1]Push Function [2] Pop Function [3] Elements present in Stack [4] Exit Enter your choice: 4
No comments:
Post a Comment