Tuesday, October 30, 2018

Program to evaluate simple expressions

<?php
// PHP program to evaluate a
// given expression

// A utility function to check if
// a given character is operand
function isOperand($c)
{
    return ($c >= '0' && $c <= '9');
}

// utility function to find
// value of and operand
function 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
?>

1 comment:

  1. Is the casino site the best place for casino site and bonus codes
    The casino site will be available and have a great selection of casino games septcasino for you to enjoy. choegocasino All your favourite casino videodl.cc games and slots

    ReplyDelete