Program to check balanced parentheses in expression c++

Program to check balanced parentheses in expression c++

Algorithm

1) Declare a character stack by STL.
2) Now traverse the expression string s.
    a) If the current character is a starting bracket ( ‘(‘ or ‘{‘ or ‘[‘ ) then push it to stack.
    b) If the current character is a closing bracket ( ‘)’ or ‘}’ or ‘]’ ) then pop from stack and match for relevant parenthesis, if match pop it from stack.
3) After complete traversal, if there is some starting bracket left in stack then parenthesis in giver expression or string are “not balanced”.

Program to check balanced parentheses in expression c++

 

 

Output

Write a program to check for balanced parentheses in an expression in c++

Suggested Reading

  1. Write a C program to reverse the words in a sentence in place
  2. Write your own trim() or squeeze() function to remove the spaces from a string
  3. Write a C program which does wildcard pattern matching algorithm