C++ Program to Check for balanced parentheses in an expression














































C++ Program to Check for balanced parentheses in an expression



Program:
 #include <iostream>
#include <stack>
using namespace std;
bool isBalancedExp(string exp) {
   stack<char> stk;
   char x;
   for (int i=0; i<exp.length(); i++) {
      if (exp[i]=='('||exp[i]=='['||exp[i]=='{') {
         stk.push(exp[i]);
         continue;
      }
      if (stk.empty())
         return false;
      switch (exp[i]) {
      case ')':
         x = stk.top();
         stk.pop();
         if (x=='{' || x=='[')
            return false;
         break;
      case '}':
         x = stk.top();
         stk.pop();
         if (x=='(' || x=='[')
            return false;
         break;
      case ']':
         x = stk.top();
         stk.pop();
         if (x =='(' || x == '{')
            return false;
         break;
      }
   }
   return (stk.empty());
}
int main() {
   string expresion = "()[(){()}]";
   if (isBalancedExp(expresion))
      cout << "This is Balanced Expression";
   else
      cout << "This is Not Balanced Expression";
}
Output:
This is Balanced Expression


More Articles of Shaik Aftab Ahmed:

Name Views Likes
C++ Program to Find the Frequency of Odd & Even Numbers in the given Matrix 299 1
C++ program to Sort a Linked List Using Merge Sort 278 1
C++ Program to Implement a Linked List representation of a Binary tree 266 1
C++ Program to Check for balanced parentheses in an expression 177 1
C++ Program to Perform Inorder, Preorder, Postorder traversals in a binary tree. 226 1
C++ program to print Indian flag 265 1
C++ program to Convert a multi level linked list to a singly linked list 174 1
C++ program to print right view of a Binary tree using queue 194 1
C++ Program to implement Huffman Coding Compression Algorithm 773 1
C++ Program to Create a Height Balanced Binary Tree 211 1
C++ program to implement Prims algorithm 299 1
C++ Program for BFS Traversal 215 1
C++ Progam to Evaluate a Prefix Expression 203 1
C++ Program to Implement Queue using Linked List 206 1
C++ implementation of Stack using Linked list 222 1
C++ program to find the intersection point of two linked lists 253 1
C++ program to count the inversions in the given array 232 1
C++ program to perform D.N.F sort 275 1
C++ program to print all possible subsets of a String 247 1
C++ program to count the number of ones in a binary representation of a number 255 1
C++ program to print all possible subsets of a set 277 1
C++ program to find the largest word in a String 240 1
C++ Program to print a matrix in Spiral order 268 1
C++ program to convert from Binary to Decimal, Octal to Decimal, Hexadecimal to Decimal 263 1
C limits library 294 1
Program to add two Binary numbers 256 1

Comments