Answer to Question #252898 in C++ for Praveen

Question #252898
Design and develop programs for evaluating the equations: Implement it
1
Expert's answer
2021-10-18T02:33:12-0400
#include <bits/stdc++.h>
using namespace std;


bool isExp(char c)
{
    if (c >= '0' && c <= '9')
    {
        return true;
    }
    return false;
}


int charToInt(char c) { return (c - '0'); }


int evaluate(char *exp)
{
    if (*exp == '\0')
        return -1;


    int ans = charToInt(exp[0]);


    for (int i = 1; exp[i]; i += 2)
    {
        char opr = exp[i], opd = exp[i + 1];
        if (!isExp(opd))
            return -1;
        if (opr == '+')
            ans += charToInt(opd);
        else if (opr == '-')
            ans -= charToInt(opd);
        else if (opr == '*')
            ans *= charToInt(opd);
        else if (opr == '/')
            ans /= charToInt(opd);
        else
            return -1;
    }
    return ans;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS