C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed

Here is another homework assignment which was presented in a C++ Data Structures course. This assignment was used to introduce the stack ADT, and helped prepare our class for two later assignments which required using a stack. Those assignments can be found here:

(1) Stack Based Infix To Postfix Conversion (Single Digit)
(2) Stack Based Postfix Evaluation (Single Digit)

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Stack Data Structure
Cin.getline
#include "ClassStackListType.h"

A simple exercise for testing a stack is determining whether a set of parenthesis is “well formed” or not. What exactly is meant by that? In the case of a pair of parenthesis, for an expression to be well formed, consider the following table.

Given an expression with characters and parenthesis, ( ), [ ], and { }, our class was asked to determine if an expression was well formed or not by using the following algorithm:

======= WELL-FORMED EXPRESSIONS =======

This program uses a custom template.h class. To obtain the code for that class, click here.

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: the code was compile four separate times to display different output)

====== RUN 1 ======

Enter an expression and press ENTER.
((
The expression: (( is NOT well formed!!!

====== RUN 2 ======

Enter an expression and press ENTER.
(a{b[]}c)

The expression: (a{b[]}c) is well formed...

====== RUN 3 ======

Enter an expression and press ENTER.
[(7 * 28) - 1987]

The expression: [(7 * 28) - 1987] is well formed...

====== RUN 4 ======

Enter an expression and press ENTER.
{3 + [2 / 3] - (9 + 18) * 12)

The expression: {3 + [2 / 3] - (9 + 18) * 12) is NOT well formed!!!

Was this article helpful?
👍 YesNo

2 Responses to C++ || Stack – Using A Stack, Determine If A Set Of Parentheses Is Well-Formed

  1. Avatar Krushkrush says:

    how to read a file in text and make it check parenthesis using stacks?? any idea is appreciated

    • admin admin says:

      Hello, thanks for visiting

      To read a text file to check parentheses, the program flow of control would be exactly the same as the example program demonstrated on this page.

      The only thing differently you would do is, instead of using “cin” to read data into a string, you would use a file operator (such as ifstream) to read data into the program.

      Click here if you dont know how to work with files.

      Hope this helps

Leave a Reply