C++: Create a class/struct. Members: MaxSize const = 10 Define an array that hol
ID: 3794859 • Letter: C
Question
C++:
Create a class/struct.
Members:
MaxSize const = 10
Define an array that holds 10 items.
Count - indicates how many items are on the stack.
Methods:
Push - Accepts a number and adds to the top of the stack. - If the stack is full emit an error indicating full.
Pop - Returns a number from the top of the stack. - If the stack is empty, emit an error indicating the stack is empty.
IsEmpty - Returns a boolean indicating if the stack is empty.
Notes: Ask the user to choose an option:
1. Push.
2. Pop.
3. Display all elements in the stack.
4. Display the size of the stack (how many elements are in the stack). Then do as the problem lists.
Part of the output should look like this:
// 1. Push
// 2. Pop
// 3. Display the size of the stack
// 4. Display all values
// 5. Quit
//
// Enter an option: 1
// Enter a value to be pushed onto stack: 5
// ------------
// 1. Push
// 2. Pop
// 3. Display the size of the stack
// 4. Display the values of the stack
// 5. Quit
//
// Enter an option: 1
// Enter a value to be pushed onto stack: 10
// ------------
// 1. Push
// 2. Pop
// 3. Display the size of the stack
// 4. Display all values of the stack
// 5. Quit
//
// Enter an option: 2
// Value popped: 10
Explanation / Answer
#include<iostream>
using namespace std;
#define STACKSIZE 10
struct stackStruct
{
int stk[STACKSIZE];
int top; // We will use it as pointer to top of the stack
} stck; // Here stck is struct variable, you can see here how to implement structure in C
void push(); // To push elements in stack
int pop(); // To Pop elements in stack
void display();
int main()
{
int index;
stck.top=-1; //Set stck to -1
int x=1;
while(x) //While loop to keep program in loop
{
cout<<" Pointer is at : "<<stck.top+1<<endl; //this line is to test, the position of stck
cout<<" Please enter your choice :"<<endl<<"1: Push"<<endl<<"2: Pop"<<endl<<"3: Display"<<endl<<"4: Exit"<<endl;
cin>>index;
switch(index)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return 0;
}
cout<<" Do you want to cotinue....? press 1 or 0"<<endl;
cin>>x;
}
}
void push()
{
int num;
if(stck.top==(STACKSIZE-1))
{
cout<<" Sorry You can't push any element into stack .... ,Stack is full";
}
else
{
cout<<" Enter the number to push into stack";
cin>>num;
stck.top+=1;
stck.stk[stck.top]= num;
}
}
int pop()
{
int num;
if(stck.top==-1)
{
cout<<" stack is empty "<<endl;
}
else
{
num=stck.top;
cout<<" Poped number is : "<<stck.stk[num];
stck.stk[num]=0; //To delete top element from stack
stck.top-=1;
}
return num;
}
void display()
{
if(stck.top==-1)
{
cout<<" Stack is empty"<<endl;
}
else
{
cout<<"Elements in the stack are:";
for(int i=stck.top;i>=0;i--)
{
cout<<" "<<i<<","<<stck.stk[i]<<endl;
}
cout<<stck.top;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.