C Saved Program: beautiful-life

facebook share

Here's the online compiler accompanied with IDE at your service. This is a saved code by one of our users. Try it out or save your own from the IDE page and don't forget to leave a feedback. You can find that at the bottom of the page.


#include<stdio.h>
#include<stdlib.h>
#define SIZE 10
struct Stack
{
	int a[10];
	int tos;
};

void push(struct Stack *s,int ele)
{

	if(s->tos==SIZE-1)
	{
	printf("Stack is Full\n");//Stack Overflow
	return;
	}
	else
	{
	(s->tos)++;
	s->a[s->tos]=ele;
	}
}

int pop(struct Stack *s)
{
	if(s->tos==-1)
	{
	printf("Stack is Empty\n");//Stack Underflow
	return -1;
	}
	else
	{
	int x;
	x=s->a[s->tos];
	s->tos--;
	return x;
	}
}

int isEmpty(struct Stack s)		//As there are no changes made to the stack, Call by value is used 
{
	if(s.tos==-1)
		return 1;//Stack is Empty
	else
		return 0;//Stack is not Empty
}

int peek(struct Stack s)		//As there are no changes made to the stack, Call by value is used 
{
	if(s.tos==-1)
	{
		printf("Stack is Empty\n");//Stack Underflow
		return -1;
	}
	else
		return s.a[s.tos];//return the topmost element of stack
}	

void display(struct Stack s)
{
	int i;
	if(s.tos==-1)
	{
		printf("No elements to display\n");
		return;
	}
	printf("The stack is:\t");
	for(i=s.tos;i>=0;i--)
	{
		printf("%d\t",s.a[i]);//Displaying the stack from top to end 
	}
}


int main()
{
	int i,y,x,ele;	
	struct Stack s;
	s.tos=-1;		//intialising the top of stack

	printf("1. Push Element\n");
	printf("2. Pop Element\n");
	printf("3. Stack is Empty or not?\n");
	printf("4. Peek the Element from Top of Stack\n");
	printf("5.Display the Stack\n");
	do
	{
		printf("Enter the Choice\t");
		scanf("%d",&i);
	
		switch(i)
		{
			case 1:/*Push element*/
				printf("Enter the Element to be Pushed\t");
				scanf("%d",&ele);
				push(&s,ele);
			break;
			
			case 2:/*pop the element*/
				x=pop(&s);
				if(x!=-1)
				printf("The popped element is \t%d",x);
			break;
			
			case 3:/*Is empty or not*/
				if(isEmpty(s))
					printf("Stack is Empty\n");
				else 
					printf("Stack is not Empty\n");
			break;
			
			case 4:/*Peek the element from top of stack*/
				if(peek(s)!=-1)
					printf("\nThe Element on Top of Stack is %d",peek(s));
			break;

			case 5:/*Display stack*/
				display(s);
			break;

			default:
				printf("\nInvalid Choice");
		}
	
	printf("\nDo you want to Continue?1-Yes,0-No");
	scanf("%d",&y);
	}while(y==1);
return 0;
}
Execute

Output

Press the execute button or CTRL + enter to run code.

Inputs