Looping operations

79 views Asked by At

I would like to write something like this;

for (op1 in (plus, minus, times, divby, exponent)) {
    printf("%d", a op1 b);
}

so that what actually ends up being executed is something like this

printf("%d", a + b);
printf("%d", a - b);
printf("%d", a * b);
printf("%d", a / b);
printf("%d", a ^ b);

How can I write this?

2

There are 2 answers

0
artm On BEST ANSWER

Array of function pointers would do.

double plus(int a, int b);
double minus(int a, int b);
double times(int a, int b);
double divby(int a, int b);
double exponent(int a, int b);

typedef double (*p_fun)(int a, int b);

int main()
{
    int a = 5, b = 10;
    p_fun pa[] = {plus, minus, times, divby, exponent};
    for( int i = 0; i < sizeof(pa)/sizeof(p_fun); i++ )
    {
        printf("%f\n", pa[i](a, b));
    }
    return 0;
}
0
Sourav Ghosh On

Since you've not posted any code, I'm not going to write any, but will be happy to help with some concepts which you can turn into working code.

  1. Write functions to perform individual operations (addition, subtraction, multiplication etc).

  2. Take an array of function pointers, initialize that with individual functions you want to perform.

  3. Loop over the array and pass the required variables to the function call to get desired output.

Something like (pseudo-code)

funcptr arr[SIZE] = { func1, func2, func3... };

for (int i = 0; i < SIZE ; i++) {
    printf("%d\n", arr[i](a, b));
}

That said, just a note, a ^ b is not an "exponent" operator in C, as you might have expected. It is bitwise XOR. You can make use of pow() to get that done.

FYI, you can refer to this question for related information.