DreamsCoder.com

We Code your Dreams


home > Program To show whether expression have matching parenthesis or not using C++




Program To show whether expression have matching parenthesis or not using C++





/*Header File - dreamscoder.h */

#include
class stk
{
   char stack[100],ch;
   int top;
   public:
   stk()
   {
     top=-1;
   }
   void push (char ch)
   {
       stack[++top]=ch;
    }
    char pop()
    {

       return(stack[top--]);
    }
   int isempty()
    {
       if(top==-1)
       {
	// printf("\nStack empty");
	  return(1);
       }
	return(0);
    }
int    isfull()
    {
       if(top>99)
       {
	  printf("\nStack full");
	 return(0);
       }
       return(1);
    }
};
___________________________________________

/*Main Program*/

#include
#include
#include"dreamscoder.h"

void main()
{
        stack s;
        boolean flag;
        char exp[100],ch,ch1;
        int i;

        clrscr();

        cout << "\nEnter An Expression : ";
        cin  >> exp;

        flag = true;

        for (i=0 ; exp[i] != '\0' ;i++)
        {
                ch = exp[i];
                if (ch == '(' || ch == '['
 || ch == '{')
                	s.push(ch);
                else
                if (ch == ')')
                {
                        ch1 = s.ret_top();
                        if (ch1 != '(')
                        {
                        	flag = false;
                                break;
                        } // if
                        else
                        	s.pop(ch1);
                } // else if
                else
                if (ch == ']')
                {
                        ch1 = s.ret_top();
                        if (ch1 != '[')
                        {
                        	flag = false;
                                break;
                        } // if
                        else
                        	s.pop(ch1);
                } // else if
                else
                if (ch == '}')
                {
                	ch1 = s.ret_top();
                        if (ch1 != '{')
                        {
                        	flag = false;
                                break;
                        } // if
                        else
                        	s.pop(ch1);
                } // else if
        } // for

        if (s.isempty() && flag)
        	cout << "\nThe Expression 
Is Balanced.";
        else
        	cout << "\nThe Expression 
Is Not Balanced.";

} // main

Label - data-structure





by - Chinmay Mahajan





Are you looking for something else?


Suggested Programs




Simple code in C for Binary tree traversal: Preorder, Inorder and Postorder


Printing the singly linked list in reverse order using recursion in C


Singly Link List program in C along with code - [Explained in Video]


Breadth first search in C Language


Dynamic Queue program using C++