Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

modify the code in this file, //filename: Balanced.cpp #include \"StackType.h\"

ID: 440624 • Letter: M

Question

modify the code in this file,

//filename: Balanced.cpp

#include "StackType.h"

#include <iostream>

using namespace std;


bool IsOpen(char symbol);

bool IsClosed(char symbol);

bool Matches(char symbol, char openSymbol);


int main()

{

char symbol;

StackType stack;

bool balanced = true;

char openSymbol;

cout << "Enter an expression and press return." << endl;

cin.get(symbol);


while (symbol != ' ' && balanced)

{

if (IsOpen(symbol))

stack.Push(symbol);


else if (IsClosed(symbol))

{

if (stack.IsEmpty())

balanced = false;

else

{

openSymbol = stack.Top();

stack.Pop();

balanced = Matches(symbol, openSymbol);

}

}

cin.get(symbol);

}

if (balanced)

cout << "Expression is well formed." << endl;

else

cout << "Expression is not well formed." << endl;

return 0;

}

bool IsOpen(char symbol)

{

if (symbol == '(' || symbol == '{' || symbol == '[')

return true;

else

return false;

}


bool IsClosed(char symbol)

{

if (symbol == ')' || symbol == '}' || symbol == ']')

return true;

else

return false;

}


bool Matches(char symbol, char openSymbol)

{

return ((openSymbol == '(' && symbol == ')')

|| (openSymbol == '{' && symbol == '}')

|| (openSymbol == '[' && symbol == ']'));

}


Explanation / Answer

The problem arises when you have opening braces without closing ones. This is because the flag balanced is set to true when you encounter a '(' . Now if your input has a single ( , say, then the balanced flag remains true and the ( is already pushed in the stack. But since you do not find a corresponding closing bracket, setting the flag to balanced is not correct. You need to set the balanced flag to true iff you encounter an opening and its closing brace both, not one alone! Cheers! Please rate:)