{"id":27141,"date":"2018-01-05T20:39:31","date_gmt":"2018-01-05T15:09:31","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27141"},"modified":"2018-01-05T20:39:31","modified_gmt":"2018-01-05T15:09:31","slug":"c-programming-program-evaluate-simple-expressions","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-program-evaluate-simple-expressions\/","title":{"rendered":"C++ Programming &#8211; Program to evaluate simple expressions"},"content":{"rendered":"<p>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.<span id=\"more-142552\"><\/span><br \/>\nTest cases:<br \/>\na) 1+2*3 will be evaluated to 9.<br \/>\nb) 4-2+6*3 will be evaluated to 24.<br \/>\nc) 1++2 will be evaluated to -1(INVALID).<br \/>\nAlso, in the string spaces can occur. For that case we need to ignore the spaces. Like :- 1*2 -1 is equals to 1.<\/p>\n<p>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.<\/p>\n<p>Following is C++ program to evaluate the given expression.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++ Program<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program to evaluate a given expression<br\/>#include &lt;ioexpeam&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ A utility function to check if a given character is operand<br\/>bool isOperand(char c) { return (c &gt;= &#039;0&#039; &amp;&amp; c &lt;= &#039;9&#039;); }<br\/> <br\/>\/\/ utility function to find value of and operand<br\/>int value(char c) {  return (c - &#039;0&#039;); }<br\/> <br\/>\/\/ This function evaluates simple expressions. It returns -1 if the<br\/>\/\/ given expression is invalid.<br\/>int evaluate(char *exp)<br\/>{<br\/>    \/\/ Base Case: Given expression is empty<br\/>    if (*exp == &#039;\\0&#039;)  return -1;<br\/> <br\/>    \/\/ The first character must be an operand, find its value<br\/>    int res = value(exp[0]);<br\/> <br\/>    \/\/ Traverse the remaining characters in pairs<br\/>    for (int i = 1; exp[i]; i += 2)<br\/>    {<br\/>        \/\/ The next character must be an operator, and<br\/>        \/\/ next to next an operand<br\/>        char opr = exp[i], opd = exp[i+1];<br\/> <br\/>        \/\/ If next to next character is not an operand<br\/>        if (!isOperand(opd))  return -1;<br\/> <br\/>        \/\/ Update result according to the operator<br\/>        if (opr == &#039;+&#039;)       res += value(opd);<br\/>        else if (opr == &#039;-&#039;)  res -= value(opd);<br\/>        else if (opr == &#039;*&#039;)  res *= value(opd);<br\/>        else if (opr == &#039;\/&#039;)  res \/= value(opd);<br\/> <br\/>        \/\/ If not a valid operator<br\/>        else                  return -1;<br\/>    }<br\/>    return res;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main()<br\/>{<br\/>    char expr1[] = &quot;1+2*5+3&quot;;<br\/>    int res = evaluate(expr1);<br\/>    (res == -1)? cout &lt;&lt; expr1 &lt;&lt; &quot; is &quot; &lt;&lt; &quot;Invalid\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Value of &quot; &lt;&lt; expr1 &lt;&lt; &quot; is &quot; &lt;&lt; res &lt;&lt; endl;<br\/> <br\/>    char expr2[] = &quot;1+2*3&quot;;<br\/>    res = evaluate(expr2);<br\/>    (res == -1)? cout &lt;&lt; expr2 &lt;&lt; &quot; is &quot; &lt;&lt; &quot;Invalid\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Value of &quot; &lt;&lt; expr2 &lt;&lt; &quot; is &quot; &lt;&lt; res &lt;&lt; endl;<br\/> <br\/>    char expr3[] = &quot;4-2+6*3&quot;;<br\/>    res = evaluate(expr3);<br\/>    (res == -1)? cout &lt;&lt; expr3 &lt;&lt; &quot; is &quot; &lt;&lt; &quot;Invalid\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Value of &quot; &lt;&lt; expr3 &lt;&lt; &quot; is &quot; &lt;&lt; res &lt;&lt; endl;<br\/> <br\/>    char expr4[] = &quot;1++2&quot;;<br\/>    res = evaluate(expr4);<br\/>    (res == -1)? cout &lt;&lt; expr4 &lt;&lt; &quot; is &quot; &lt;&lt; &quot;Invalid\\n&quot;:<br\/>                 cout &lt;&lt; &quot;Value of &quot; &lt;&lt; expr4 &lt;&lt; &quot; is &quot; &lt;&lt; res &lt;&lt; endl;<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Value of 1+2*5+3 is 18\r\nValue of 1+2*3 is 9\r\nValue of 4-2+6*3 is 24\r\n1++2 is Invalid<\/pre>\n<p>The above code doesn\u2019t 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.<\/p>\n<p>Time Complexity is O(n) where n is length of the given expression.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming &#8211; Program to evaluate simple expressions &#8211; Algorithm &#8211; string that represent an expression of digits and operands. E.g. 1+2*3, 1-2+4. <\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,83515,1],"tags":[74843,69926,74830,80915,74826,80911,80912,75654,80914,80917,76278,69952,78357,74838],"class_list":["post-27141","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-c-programming-3","category-coding","tag-arithmetic-operators-in-c","tag-c-language-basics-notes","tag-c-programming-basics-notes","tag-c-programming-conditional-operator","tag-c-programming-switch","tag-c-type-casting","tag-conditional-expression-in-c","tag-conditional-operator-in-c","tag-conditional-operators-in-c","tag-variable-declaration-in-c","tag-various-operators-in-c","tag-what-is-c-language-definition","tag-what-is-in-c-language","tag-while-loop-in-c-programming-example"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27141","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27141"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27141\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27141"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27141"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27141"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}