Q:

Creating a calculator in C

How can I create a calculator in C without using if else and switch case ?
Here is the code so far :
void main()

{

    int a,b,sum,sub,pro,divide; /** sum is for addition,,sub is for subtraction,,pro is for product,,divide is for division**/
    char operator;
    clrscr();      
    printf("enter a value:");
    scanf("%d",&a);      
    printf("enter another value:");
    scanf("%d",&b);
    printf("enter a operator:");
    scanf("%c",&operator);

    operator=='+';
    sum=a+b;
    printf("\nAnswer=%d",sum);
    operator=='-'
   sub=a-b;
    printf("\nAnswer=%d",sub);
    operator=='*';
    pro=a*b;
    prinf("\nAnswer=%d",pro);
    operator=='/';
    printf("\nAnswer=%d",divide);
    getch();  

}

A:

The following should do the trick. It avoids using if else and switch by taking advantage of the fact that comparing the operator to either of +, -, * or / will return 1 for only one of the comparisons and 0 for the rest. Therefore the result is the sum of these comparisons, multiplied by the mathematic expression that corresponds to each operator:
#include<stdio.h>

main(){
    float a,b,result;
    char oper [2];
    printf("enter a value:");
    scanf("%f",&a);
    printf("enter another value:");
    scanf("%f",&b);
    printf("enter an operator:");
    scanf("%1s", oper);
    result = (oper[0] == '+') * (a + b) +
             (oper[0] == '-') * (a - b) +
             (oper[0] == '*') * (a * b) +
             (oper[0] == '/') * (a / b);
    printf("%4.2f %s %4.2f = %4.2f\n", a, oper, b, result);
}

When saved to a file called calculator.c the following command will compile it:
gcc calculator.c

The output will be called a.out and it can be run like this:
./a.out
enter a value:24
enter another value:4
enter an operator:/
24.00 / 4.00 = 6.00

I've been using gcc (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2) but I'm sure other versions will work just as well.
Let me know if I pass your assignment ;-)

