Check if given Parentheses expression is balanced or not | C ++ program for the above approach . ; Function to check if parentheses are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more Closing parenthesis than opening ones ; If count is not zero , It means there are more opening parenthesis ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBalanced ( string exp ) { bool flag = true ; int count = 0 ; for ( int i = 0 ; i < exp . length ( ) ; i ++ ) { if ( exp [ i ] == ' ( ' ) { count ++ ; } else { count -- ; } if ( count < 0 ) { flag = false ; break ; } } if ( count != 0 ) { flag = false ; } return flag ; } int main ( ) { string exp1 = " ( ( ( ) ) ) ( ) ( ) " ; if ( isBalanced ( exp1 ) ) cout << " Balanced ▁ STRNEWLINE " ; else cout << " Not ▁ Balanced ▁ STRNEWLINE " ; string exp2 = " ( ) ) ( ( ( ) ) " ; if ( isBalanced ( exp2 ) ) cout << " Balanced ▁ STRNEWLINE " ; else cout << " Not ▁ Balanced ▁ STRNEWLINE " ; return 0 ; }