C# code to Validate Mathematical Expression

Manojjupally
Posted by Manojjupally under C# category on | Points: 40 | Views : 4228
Validate Mathematical Expression in C#


class ValidateMathematicalExpression
{
public static int top;
static int f;
class Stack
{
private char[] stackArray = new char[20];
public Stack()
{
top = -1;
}

public void Push(char x)
{
top++;
stackArray[top] = x;
}

public char Pop()
{
if (top != -1)
{
top--;
return stackArray[top + 1];
}
else
return '0';
}

}
public static void ValidateExpression(string Expression)
{
char[] charExp = Expression.ToCharArray();
Stack myStack = new Stack();


for (int i = 0; i < charExp.Length; i++)
{
switch (charExp[i])
{
case '(':
{
myStack.Push(charExp[i]);
break;
}
case '{':
{
myStack.Push(charExp[i]);
break;
}
case ')':
{
if (myStack.Pop() != '(')
f = 1;
break;
}
case '}':
{
if (myStack.Pop() != '{')
f = 1;
break;
}
}
}

if (f == 0 && top == -1)
{
Console.WriteLine("Valid Expression");
}
else
{
Console.WriteLine("In Valid Expression");
}
}
}

Comments or Responses

Login to post response