What are the two arithmetic operations? Can the input values, 0 or 1, be incorperated into the arithmetic function?

Printable View

- 01-13-2013megafiddle
What are the two arithmetic operations? Can the input values, 0 or 1, be incorperated into the arithmetic function?

- 01-13-2013Click_here
As laserlight pointed out, it is not at a beginner level -> But I'm sure that the OP can appreciate that it can be done.

However, if you are only adding two numbers, you could use arrays to input the two different numbers and the input to determine the offset from the start of the array.

Code:`int main(int argc, const char *argv[])`

{

int user_in=0;

int arr_offset, answer;

int lookup_arr[6] = {0, 0, 1, 2, 3, 4};

printf("Enter 1 for 1 + 2, or \nEnter 2 for 3 + 4\n");

scanf("%d", &user_in);

arr_offset = 2 * user_in * ((unsigned int)user_in <= 2);

answer = lookup_arr[arr_offset] + lookup_arr[arr_offset+1];

printf("Output: %d + %d = %d", lookup_arr[arr_offset], lookup_arr[arr_offset+1], answer);

return EXIT_SUCCESS;

}

- 01-13-2013iMalc
If its just arithmetic operations then no arrays or function pointers are needed.

Just perfrom both calculations in one large expression, multiplying one part by the user_input, and the other part by (1-user_input).

Although in all liklihood, it can be simplified even further from there. - 01-14-2013c99tutorialCode:
`double addition(double a, double b) { return a + b; }`

double subtraction(double a, double b) { return a - b; }

int main(void)

{

int choice;

printf("Enter 0 for addition or 1 for subtraction: ");

scanf("%d", &choice);

double a, b;

printf("Enter two numbers a b: ");

scanf("%lf %lf", &a, &b);

double result = 0.0;

result += !choice * addition(a, b);

result += choice * subtraction(a, b);

printf("Result is %g\n", result);

}