Saturday, February 7, 2015

validation of infix expression in C++

#include<iostream>
#include<cstring>
using namespace std;
class stack
{
int top;
int size;
char elmnt[50];
public:
void push(char ch);
char pop();
stack()
{
top=-1;
size=50;
}
}s;
void stack::push(char ch)
{
elmnt[++top]=ch;
}
char stack::pop()
{
return(elmnt[--top]);
}
void check(char arr[],int l)
{
int i,flag;
char c;
for(i=0;i<l;i++)
{
flag=0;
if(arr[i]=='(' || '{' || '[')
{
if(arr[i]=='(')
s.push(')');
if(arr[i]=='{')
s.push('}');
else
s.push(']');
}
else if(arr[i]==')' || arr[i]=='}' || arr[i]==']')
{
if(arr[i]==')')
{
c=s.pop();
if(c!=')')
{
flag=1;
break;
}
}
if(arr[i]=='}')
{
c=s.pop();
if(c!='}')
{
flag=1;
break;
}
}
else
{
c=s.pop();
if(c!=']')
{
flag=1;
break;
}
}
}
}
cout<<"The Expression is ";
if(flag==1)
cout<<"Not Balanced";
else
cout<<"Balanced";
}
int main()
{
int l;
char arr[50];
cout<<"Enter the Infix Expression...\n";
cin.getline(arr,50);
l=strlen(arr);
check(arr,l);
}

No comments:

Post a Comment

Contributors

Translate