0% found this document useful (0 votes)
33 views

Stack Using Array

This C program implements a stack using an array. It defines a stack struct with a top variable and element array. Main initializes the stack pointer, offers menu options to push, pop, or peek the top element, and continues in a loop until the user enters 'n'. The push function checks for overflow before incrementing top and storing the value. Pop decrements top and returns the removed element or -2 if empty. Peek simply returns the top element without removing it.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Stack Using Array

This C program implements a stack using an array. It defines a stack struct with a top variable and element array. Main initializes the stack pointer, offers menu options to push, pop, or peek the top element, and continues in a loop until the user enters 'n'. The push function checks for overflow before incrementing top and storing the value. Pop decrements top and returns the removed element or -2 if empty. Peek simply returns the top element without removing it.

Uploaded by

happyskd1993
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Stack using array

#include<stdio.h> #include<conio.h> #define MAX 10 struct stack { int top; int element[MAX]; }; struct stack *s; void push(int value); int pop(); int peek(); int isfull(); int isempty(); void main() { int info,a,x,y; char ch; clrscr(); s->top=-1; do { printf("Enter your choice\n1:Push\n2:Pop\n"); printf("3:Access the top element\n"); scanf("%d",&a); if(a==1) { printf("Enter the element\n"); scanf("%d",&info); push(info); } else if(a==2) { x=pop(); if(x==-2) { printf("Stack Empty\n"); } else { printf("Element deleted: %d\n",x); } } else if(a==3) { y=peek(); printf("Top element: %d\n",y); } printf("Do you want to continue? y/n\n"); scanf(" %c",&ch);

clrscr(); } while(ch=='y'); } getch();

void push(int value) { int x; x=isfull(); if(x==1) { return; } else { s->top++; s->element[s->top]=value; } } { int value,x; x=isempty(); if(x==1) { return -2; } else { value=s->element[s->top]; s->top--; return value; }

int peek() { return (s->element[s->top]); } int isfull() { if(s->top==MAX) { printf("Stack Overflow\n"); return 1; } else return 0; } int isempty() { if(s->top==-1) { return 1; }

else return 0;

Output

You might also like