Program to evaluate simple expressions

03 Nov, 2021
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.Source: Amazon Interview QuestionIt is strongly recommend to minimize the browser and try this yourself first. The idea is simple start from the first character and traverse from left to right and check for errors like two consecutive operators and operands. We also keep track of result and update the result while traversing the expression.Following is the program to evaluate the given expression.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to evaluate a given expression#include <iostream>using namespace std; // A utility function to check if a given character is operandbool isOperand(char c) { return (c >= '0' && c <= '9'); } // utility function to find value of and operandint value(char c) {  return (c - '0'); } // This function evaluates simple expressions. It returns -1 if the// given expression is invalid.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;} // Driver program to test above functionint main(){    char expr1[] = "1+2*5+3";    int res = evaluate(expr1);    (res == -1)? cout << expr1 << " is " << "Invalid\n":                 cout << "Value of " << expr1 << " is " << res << endl;     char expr2[] = "1+2*3";    res = evaluate(expr2);    (res == -1)? cout << expr2 << " is " << "Invalid\n":                 cout << "Value of " << expr2 << " is " << res << endl;     char expr3[] = "4-2+6*3";    res = evaluate(expr3);    (res == -1)? cout << expr3 << " is " << "Invalid\n":                 cout << "Value of " << expr3 << " is " << res << endl;     char expr4[] = "1++2";    res = evaluate(expr4);    (res == -1)? cout << expr4 << " is " << "Invalid\n":                 cout << "Value of " << expr4 << " is " << res << endl;    return 0;}
// Java program to evaluate a given expression class GFG{// A utility function to check if// a given character is operandstatic boolean isOperand(char c){    return (c >= '0' && c <= '9');     } // utility function to find value of and operandstatic int value(char c){    return (int)(c - '0');     } // This function evaluates simple expressions.// It returns -1 if the given// expression is invalid.static int evaluate(String exp){    // Base Case: Given expression is empty    if (exp.length() == 0) return -1;     // The first character must be    // an operand, find its value    int res = value(exp.charAt(0));     // Traverse the remaining characters in pairs    for (int i = 1; i<exp.length(); i += 2)    {        // The next character must be an operator, and        // next to next an operand        char opr = exp.charAt(i), opd = exp.charAt(i+1);         // If next to next character is not an operand        if (isOperand(opd) == false) 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;} // Driver program to test above functionpublic static void main(String[] args){    String expr1 = "1+2*5+3";    int res = evaluate(expr1);    if(res == -1) System.out.println(expr1+" is Invalid");    else     System.out.println("Value of "+expr1+" is "+res);     String expr2 = "1+2*3";    res = evaluate(expr2);    if(res == -1) System.out.println(expr2+" is Invalid");    else         System.out.println("Value of "+expr2+" is "+res);     String expr3 = "4-2+6*3";    res = evaluate(expr3);    if(res == -1) System.out.println(expr3+" is Invalid");    else         System.out.println("Value of "+expr3+" is "+res);     String expr4 = "1++2";    res = evaluate(expr4);    if(res == -1) System.out.println(expr4+" is Invalid");    else         System.out.println("Value of "+expr4+" is "+res);}}// This code is contributed by mits
# Python3 program to evaluate a# given expression # A utility function to check if# a given character is operanddef isOperand(c):      return (c >= '0' and c <= '9'); # utility function to find# value of and operanddef value(c):    return ord(c) - ord('0'); # This function evaluates simple# expressions. It returns -1 if the# given expression is invalid.def evaluate(exp):     len1 = len(exp);         # Base Case: Given expression is empty    if (len1 == 0):        return -1;     # The first character must be    # an operand, find its value    res = value(exp[0]);     # Traverse the remaining    # characters in pairs    for i in range(1,len1,2):        # The next character must be        # an operator, and next to        # next an operand        opr = exp[i];        opd = exp[i + 1];         # If next to next character        # is not an operand        if (isOperand(opd)==False):            return -1;         # Update result according        # to the operator        if (opr == '+'):            res += value(opd);        elif (opr == '-'):            res -= int(value(opd));        elif (opr == '*'):            res *= int(value(opd));        elif (opr == '/'):            res /= int(value(opd));         # If not a valid operator        else:            return -1;         return res; # Driver Codeexpr1 = "1+2*5+3";res = evaluate(expr1);print(expr1,"is Invalid") if (res == -1) else print("Value of",expr1,"is",res); expr2 = "1+2*3";res = evaluate(expr2);print(expr2,"is Invalid") if (res == -1) else print("Value of",expr2,"is",res); expr3 = "4-2+6*3";res = evaluate(expr3);print(expr3,"is Invalid") if (res == -1) else print("Value of",expr3,"is",res); expr4 = "1++2";res = evaluate(expr4);print(expr4,"is Invalid") if (res == -1) else print("Value of",expr4,"is",res); # This code is contributed by mits
// C# program to evaluate a given expressionusing System;class GFG{     // A utility function to check if// a given character is operandstatic bool isOperand(char c) {    return (c >= '0' && c <= '9');     } // utility function to find value of and operandstatic int value(char c) { return (int)(c - '0'); } // This function evaluates simple// expressions. It returns -1 if the// given expression is invalid.static int evaluate(string exp){    // Base Case: Given expression is empty    if (exp.Length == 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; i<exp.Length; 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)==false) 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;} // Driver program to test above functionstatic void Main(){    string expr1 = "1+2*5+3";    int res = evaluate(expr1);    if(res == -1)    Console.WriteLine(expr1+" is Invalid");    else        Console.WriteLine("Value of "+expr1+" is "+res);     string expr2 = "1+2*3";    res = evaluate(expr2);    if(res == -1)    Console.WriteLine(expr2+" is Invalid");    else            Console.WriteLine("Value of "+expr2+" is "+res);     string expr3 = "4-2+6*3";    res = evaluate(expr3);    if(res == -1)    Console.WriteLine(expr3+" is Invalid");    else            Console.WriteLine("Value of "+expr3+" is "+res);     string expr4 = "1++2";    res = evaluate(expr4);    if(res == -1)    Console.WriteLine(expr4+" is Invalid");    else            Console.WriteLine("Value of "+expr4+" is "+res);}}// This code is contributed by mits
<?php// PHP program to evaluate a// given expression // A utility function to check if// a given character is operandfunction isOperand($c){    return ($c >= '0' && $c <= '9');} // utility function to find// value of and operandfunction value($c){    return ($c - '0');} // This function evaluates simple// expressions. It returns -1 if the// given expression is invalid.function evaluate($exp){    $len = strlen($exp);         // Base Case: Given expression is empty    if ($len == 0) return -1;     // The first character must be    // an operand, find its value    $res = (int)(value($exp[0]));     // Traverse the remaining    // characters in pairs    for ($i = 1; $i < $len; $i += 2)    {        // The next character must be         // an operator, and next to        // next an operand        $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 -= (int)(value($opd));        else if ($opr == '*')            $res *= (int)(value($opd));        else if ($opr == '/')            $res /= (int)(value($opd));         // If not a valid operator        else                       return -1;    }    return $res;} // Driver Code$expr1 = "1+2*5+3";$res = evaluate($expr1);($res == -1) ? print($expr1." is Invalid\n"):               print("Value of " . $expr1 .                     " is " . $res . "\n");             $expr2 = "1+2*3";$res = evaluate($expr2);($res == -1) ? print($expr2." is Invalid\n"):               print("Value of " . $expr2 .                     " is " . $res . "\n");             $expr3 = "4-2+6*3";$res = evaluate($expr3);($res == -1) ? print($expr3." is Invalid\n"):               print("Value of " . $expr3 .                     " is " . $res . "\n");             $expr4 = "1++2";$res = evaluate($expr4);($res == -1) ? print($expr4." is Invalid\n"):               print("Value of " . $expr4 .                     " is " . $res . "\n"); // This code is contributed by mits?>
<script>// Javascript program to evaluate a given expression // A utility function to check if// a given character is operandfunction isOperand(c){    return (c.charCodeAt(0) >= '0'.charCodeAt(0) && c.charCodeAt(0) <= '9'.charCodeAt(0));} // utility function to find value of and operandfunction value(c){    return (c.charCodeAt(0) - '0'.charCodeAt(0));} // This function evaluates simple expressions.// It returns -1 if the given// expression is invalid.function evaluate(exp){    // Base Case: Given expression is empty    if (exp.length == 0) return -1;       // The first character must be    // an operand, find its value    let res = value(exp[0]);       // Traverse the remaining characters in pairs    for (let i = 1; i<exp.length; i += 2)    {        // The next character must be an operator, and        // next to next an operand        let opr = exp[i], opd = exp[i+1];           // If next to next character is not an operand        if (isOperand(opd) == false) 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;} // Driver program to test above functionlet expr1 = "1+2*5+3";let res = evaluate(expr1);if(res == -1) document.write(expr1+" is Invalid<br>");else     document.write("Value of "+expr1+" is "+res+"<br>"); let expr2 = "1+2*3";res = evaluate(expr2);if(res == -1) document.write(expr2+" is Invalid<br>");else         document.write("Value of "+expr2+" is "+res+"<br>"); let expr3 = "4-2+6*3";res = evaluate(expr3);if(res == -1) document.write(expr3+" is Invalid<br>");else         document.write("Value of "+expr3+" is "+res+"<br>"); let expr4 = "1++2";res = evaluate(expr4);if(res == -1) document.write(expr4+" is Invalid<br>");else         document.write("Value of "+expr4+" is "+res+"<br>");  // This code is contributed by avanitrachhadiya2155</script>
Output:  
Value of 1+2*5+3 is 18
Value of 1+2*3 is 9
Value of 4-2+6*3 is 24
1++2 is Invalid
Time Complexity: O(|exp|)
Auxiliary Space: O(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 traversal. This is left as an exercise.Time Complexity is O(n) where n is length of the given expression.This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Mithun Kumar
avanitrachhadiya2155
rishavmahato348
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to find sum of elements in a given array