Program to evaluate simple expressions | C ++ program to evaluate a given expression ; A utility function to check if a given character is operand ; utility function to find value of and operand ; This function evaluates simple expressions . It returns - 1 if the given expression is invalid . ; Base Case : Given expression is empty ; The first character must be an operand , find its value ; Traverse the remaining characters in pairs ; The next character must be an operator , and next to next an operand ; If next to next character is not an operand ; Update result according to the operator ; If not a valid operator ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; bool isOperand ( char c ) { return ( c >= '0' && c <= '9' ) ; } int value ( char c ) { return ( c - '0' ) ; } int evaluate ( char * exp ) { if ( * exp == ' \0' ) return -1 ; int res = value ( exp [ 0 ] ) ; for ( int i = 1 ; exp [ i ] ; i += 2 ) { char opr = exp [ i ] , opd = exp [ i + 1 ] ; if ( ! isOperand ( opd ) ) return -1 ; if ( opr == ' + ' ) res += value ( opd ) ; else if ( opr == ' - ' ) res -= value ( opd ) ; else if ( opr == ' * ' ) res *= value ( opd ) ; else if ( opr == ' / ' ) res /= value ( opd ) ; else return -1 ; } return res ; } int main ( ) { char expr1 [ ] = "1 + 2*5 + 3" ; int res = evaluate ( expr1 ) ; ( res == -1 ) ? cout << expr1 << " ▁ is ▁ " << " Invalid STRNEWLINE " : cout << " Value ▁ of ▁ " << expr1 << " ▁ is ▁ " << res << endl ; char expr2 [ ] = "1 + 2*3" ; res = evaluate ( expr2 ) ; ( res == -1 ) ? cout << expr2 << " ▁ is ▁ " << " Invalid STRNEWLINE " : cout << " Value ▁ of ▁ " << expr2 << " ▁ is ▁ " << res << endl ; char expr3 [ ] = "4-2 + 6*3" ; res = evaluate ( expr3 ) ; ( res == -1 ) ? cout << expr3 << " ▁ is ▁ " << " Invalid STRNEWLINE " : cout << " Value ▁ of ▁ " << expr3 << " ▁ is ▁ " << res << endl ; char expr4 [ ] = "1 + + 2" ; res = evaluate ( expr4 ) ; ( res == -1 ) ? cout << expr4 << " ▁ is ▁ " << " Invalid STRNEWLINE " : cout << " Value ▁ of ▁ " << expr4 << " ▁ is ▁ " << res << endl ; return 0 ; }