This program can solve expressions of the following forms: a+b , a-b , a*b , a/b ( a and b are numbers :P)
Notice: You can't put spaces in between the operands and the operator, I know this is a limitation and that there are thousands of other ways to achieve a better result, so please don't start complaining about this, it's just a "very simple" two-operand expression 'parser' :)

#include <stdio.h>

int calc(int op1, int op2, char op);
short op_v(char op);

int main(void)
    /* Variable declarations */
    char op;
    int op1, op2;
    /* Get the expression */
    printf("%s", "Enter a simple expression: ");
    /* Break the expression down into tokens and solve it */
    if(scanf("%d%c%d", &op1, &op, &op2) == 3 && op_v(op))
	printf("%s%d", "Result= ", calc(op1, op2, op));
	printf("%s", "Invalid expression.\n");
    return 0;

/* Calculate the result */
int calc(int op1, int op2, char op)
    case '+': return op1+op2;
    case '-': return op1-op2;
    case '*': return op1*op2;
    case '/': return op1/op2;

/* Validate the operator */
short op_v(char op)
    case '+': return 1;
    case '-': return 1;
    case '*': return 1;
    case '/': return 1;
    default: return 0;
7 Years
Discussion Span
Last Post by mvmalderen

I will not complain. This is very good to start with, but if you like this sort of things, please try to learn more about it! That is if you can and if you want to. It can be a very exciting journey!


The op_v function can be updated, by using strchr instead.
This will compact the code with 13 lines :)

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.