Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert character into arithmetic operator without using switch case i.e., convert '+' to +

Tags:

c

void main()
{
    char c;
    int op;
    int a=10,b=20,sum;

    scanf("%c",&c);
    if(c=='+')
      op=1;
    else if(c=='-')
      op=2;
    else if(c=='*')
      op=3;

    switch(op)//here i used switch but i don't want to use it
    {
       case 1: sum=a+b;
               break;
       case 2: sum=a-b;
               break;
       case 3: sum=a*b;
                break;
    }
       printf("%d",sum);

}

output should be 30 when c contains c sum should contain 30 acb should be evaluated to a+b and it should contain 30

like image 545
user3365619 Avatar asked Dec 09 '22 09:12

user3365619


2 Answers

You could simply do this:

void main()
{
    char c;
    int a=10,b=20,sum;
    scanf("%c",&c);
    sum=(c=='+')?(a+b):((c=='-')?(a-b):((c=='*')?(a*b):0));
    printf("%d",sum);
}

Don't be confused with the line sum=(c=='+')?(a+b):((c=='-')?(a-b):((c=='*')?(a*b):0));. It actually does this:

if(c=='+')
    sum=a+b;
else
{
    if(c=='-')
        sum=a-b;
    else
    {
        if(c=='*')
            sum=a*b;
        else
            sum=0;
    }
}

The operator (?:) is called Conditional (ternary) operator.

Syntax:

condition ? expr_if_condition_is_true : expr_if_condition_is_false

If the condition is true, expression1 will be returned. Else expression2 will be returned. As you can see, there are 3 nested conditional operators are used in that line.

Read more about conditional operator here.

like image 71
Raging Bull Avatar answered Dec 11 '22 11:12

Raging Bull


I'm not saying it's a good way of doing things, but you could have something like:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

typedef int (*fn)(int, int);
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }

int main(void) {
    int a = 10, b = 20, sum;
    char c;
    fn f[256] = {NULL};

    f['+'] = add;
    f['-'] = subtract;
    // etc

    scanf("%c", &c);
    fn fn = f[(int)c];
    assert(fn != NULL);
    sum = fn(a, b);
    printf("%d\n", sum);

    return EXIT_SUCCESS;
}

Realistically, though, just go with a switch statement.

like image 23
Hugh Avatar answered Dec 11 '22 11:12

Hugh