Program to evaluate simple expressions - GeeksQuiz
You are given a string that represent an expression of digits and operands. E.g. 1+2*3, 1-2+4. You need to evaluate the string or the expression. NO BODMAS is followed. If the expression is of incorrect syntax return -1.
Test cases:
a) 1+2*3 will be evaluated to 9.
b) 4-2+6*3 will be evaluated to 24.
c) 1++2 will be evaluated to -1(INVALID).
Also, in the string spaces can occur. For that case we need to ignore the spaces. Like :- 1*2 -1 is equals to 1
The above code doesn’t handle spaces. We can handle spaces by first removing all spaces from the given string. A better solution is to handle spaces in single traversa
Read full article from Program to evaluate simple expressions - GeeksQuiz
You are given a string that represent an expression of digits and operands. E.g. 1+2*3, 1-2+4. You need to evaluate the string or the expression. NO BODMAS is followed. If the expression is of incorrect syntax return -1.
Test cases:
a) 1+2*3 will be evaluated to 9.
b) 4-2+6*3 will be evaluated to 24.
c) 1++2 will be evaluated to -1(INVALID).
Also, in the string spaces can occur. For that case we need to ignore the spaces. Like :- 1*2 -1 is equals to 1
int
evaluate(
char
*
exp
)
{
// Base Case: Given expression is empty
if
(*
exp
==
'\0'
)
return
-1;
// The first character must be an operand, find its value
int
res = value(
exp
[0]);
// Traverse the remaining characters in pairs
for
(
int
i = 1;
exp
[i]; i += 2)
{
// The next character must be an operator, and
// next to next an operand
char
opr =
exp
[i], opd =
exp
[i+1];
// If next to next character is not an operand
if
(!isOperand(opd))
return
-1;
// Update result according to the operator
if
(opr ==
'+'
) res += value(opd);
else
if
(opr ==
'-'
) res -= value(opd);
else
if
(opr ==
'*'
) res *= value(opd);
else
if
(opr ==
'/'
) res /= value(opd);
// If not a valid operator
else
return
-1;
}
return
res;
}
Read full article from Program to evaluate simple expressions - GeeksQuiz