In: Computer Science
Write push and pop functions on C/C++.
Have a program having 10 random integers(hardcoded)and put them on your stack.
Also, print them. Read a character from the keyboard.
If the character is an “o” then pop from the stack but don’t print.
If the character is a “p”, then pop from the stack and print that number.
If the character is an “e” or the stack is empty, end the program.
C program
#include<stdio.h>
#include<stdlib.h>
//stack array, stack top, item decalred as integer
int top,i, stack[100],item;
char ch;
void push()//push operation insert element to stack
{
top++;
stack[top]=item;
}
void pop()//pop operation delete element at top of stack
{
item = stack[--top];
}
void display()//display function prints stack elements
{
printf("Elements in stack:");
for(i = top ; i > 0; i--)
printf("%d ",stack[i]);
printf("\n");
}
void compare()//'p', 'o' ,'e' operations are done in this function
{
scanf("%c",&ch);
if(ch == 'o') //delete top of stack
{
pop();
}
else if(ch == 'p') //delete and display top of stack
{
pop();
printf("Deleted Element is %d\n",item);
}
else if(ch == 'e')//End program
{
top = 0;
}
}
void main()
{
char ch;
top = 0;
for(int i = 0; i < 10 ; i++)//insert 10 elements in to the stack
{
item = (rand() % 11) + 10;//generate random integer
push();
}
display();
while(ch!='e' && top!=0)
{
printf("Enter character: ");
compare();
}
printf("End Program");
}
C program screenshot
OUTPUT SCREENSHOT