C++ PROGRAMMING please make sure program compiles and runs for 5 stars :-) CSC 2
ID: 3825297 • Letter: C
Question
C++ PROGRAMMING please make sure program compiles and runs for 5 stars :-)
CSC 2111 optional lab 2 objectives: Implement and utilize a stack abstract data type Question 1: Accompanying this question is a skeleton of a program that defines a Stack class, as well as a main function to read an algebraic expression from the user. Complete the main program and determine if the user has provided an expression with a balanced set of parenthesis. The mechanism for checking if the parenthesis are balanced must make use of a stack. Example outputs: Enter an expression 1 3 Balanced Parenthesis Press any key to continue Enter an expression 1 (3 5 7 Mismatched Parenthesis Press any key to continue Enter an expression 3 7) Balanced Parenthesis Press any key to continue Enter an expression 3 7 4 Mismatched Parenthesis Press any key to continueExplanation / Answer
#include<iostream>
#include<string>
using namespace std;
class Stack {
public:
Stack() {
Stack(10);
}
Stack(int capacity) : cap(capacity - 1), top(0) {
data = new char[capacity];
}
~Stack() {
delete data;
}
void push(char value);
char pop();
bool isEmpty();
private:
int top, cap;
char *data;
};
bool match(char char_1, char char_2);
void Stack::push(char value) {
if (top == cap) {
/* Full stack */
return;
}
data[top++] = value;
}
char Stack::pop() {
if (top == 0) {
/* Empty stack */
return '';
}
return data[--top];
}
bool Stack::isEmpty() {
return top == 0;
}
int main(void) {
cout << "Enter an expression" << endl;
string str;
getline(cin, str);
Stack s(15);
int mismatch = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
continue;
}
/*
* Complete me
*/
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
{
s.push(str[i]);
}
if (str[i] == ')' || str[i] == '}' || str[i] == ']')
{
if (s.isEmpty() || !match(s.pop(), str[i]))
{
if (!s.isEmpty())
{
mismatch = 1;
break;
}
}
}
}
/*
* Complete me
*/
if (!mismatch && s.isEmpty())
{
cout << "Balanced parantheses" << endl;
}
else
{
cout << "Mismatched parantheses" << endl;
}
return 0;
}
/* Match for relevent paranthesis */
bool match(char char_1, char char_2)
{
if (char_1 == '(' && char_2 == ')')
return true;
else if (char_1 == '{' && char_2 == '}')
return true;
else if (char_1 == '[' && char_2 == ']')
return true;
else
return false;
}
------------------------------------------------
//output
Enter an expression
1 + 3
Balanced parantheses
Enter an expression
1 + (3 * 5 - 7
Mismatched parantheses
Enter an expression
5 * (3 + 7)
Balanced parantheses
Enter an expression
) + 3 * ( 7 + 4
Mismatched parantheses
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.