2

I am trying to find a way to use loops in order to calculate the result of every combination of 3 operators and 4 integers, and I was wondering if there is a way to have a loop run 4 times, each time using a different operator.

It's intended to work something like this, but I'm not sure how possible it is.

int a = 2;
int b = 3;

for (int i = 0; i < 4; i++) {
   if (i == 0) {
      operator = '+';
   } else if (i == 1) {
      operator = '-';
   } else if (i == 2) {
      operator = '*';
   } else if (i == 3) {
      operator = '/';
   }

   printf("Result: %d\n", a operator b);
}

And the output would print results of 5, -1, 6, and 0...

But as I have read, operators cannot be put into variables, which is where I'm stuck.

If anyone could give me some insight as to how I could get around this, it would be greatly appreciated!

3 Answers 3

2

You can use function pointers like this:

#include <stdio.h>

#define OP_NUM 4

typedef int(*op_f)(int, int);

typedef struct _ops {
        op_f fp;
        char * ops;
}ops;

int add (int a, int b) {
        return a + b;
}

int sub (int a, int b) {
        return a - b;
}

int mul (int a, int b) {
        return a * b;
}

int dv (int a, int b) {
        return a / b;
}

int main (void) {
        ops st_op[OP_NUM] = {   {add, "+"},
                                {sub, "-"},
                                {mul, "*"},
                                {dv, "/"}
                            };

        int a = 2;
        int b = 3;

        for (int i = 0; i < OP_NUM; i++) {
                printf ("%d %s %d : %d\n", a, st_op[i].ops, b, st_op[i].fp(a, b));
        }
        return 0;
}

Output:

# ./a.out
2 + 3 : 5
2 - 3 : -1
2 * 3 : 6
2 / 3 : 0
Sign up to request clarification or add additional context in comments.

Comments

1

By far the simplest approach would be to include your operators in a character string and then loop over each character in the string passing each character through a switch() statement that evaluates your expression based on the operator, e.g.

#include <stdio.h>

int main (void) {

    int a = 2,
        b = 3;
    const char *ops = "+-*/";           /* constant string of operators */

    for (int i = 0; ops[i]; i++) {      /* loop over each operator (char) */
        int result = 0;

        switch (ops[i]) {               /* switch on each operator (char) */
            case '+': result = a + b;       /* addition */
                break;
            case '-': result = a - b;       /* subtraction */
                break;
            case '*': result = a * b;       /* multiplication */
                break;
            case '/': result = a / b;       /* division */
                break;
            default:
                fputs ("invalid operator.\n", stderr);  /* invalid operator */
                continue;                               /* go get next char */
        }
        /* output result */
        printf ("Result: %d %c %d = % d\n", a, ops[i], b, result);
    }
}

Example Use/Output

$ ./bin/switch_operator
Result: 2 + 3 =  5
Result: 2 - 3 = -1
Result: 2 * 3 =  6
Result: 2 / 3 =  0

Look things over and let me know if you have further questions.

Comments

0

If it’s important for you to separate the operation choice and its execution, you can use a function pointers:

int add(int a, int b)
{
   return a + b;
}

int sub(int a, int b)
{
   return a - b;
}

int mul(int a, int b)
{
   return a * b;
}

int dv(int a, int b)
{
   return a / b;
}


int main()
{

   int (*op)(int, int);
   int a = 2;
   int b = 3;
   int i;
   for (i = 0; i < 4; i++) {
      if (i == 0) {
         op = add;
      } else if (i == 1) {
         op = sub;
      } else if (i == 2) {
         op = mul;
      } else if (i == 3) {
         op = dv;
      }
      printf("Result: %d\n", op(a, b));
   }

   return 0;
}

Or you can simplify the if/else chain by using an array of pointers

typedef int (*OP)(int, int);
.............................
OP ops[] = {add, sub, mul, dv};
for (i = 0; i < 4; i++) {
   printf("Result: %d\n", ops[i](a, b));
}

6 Comments

Replace that if/else chain with an array of function pointers.
result = ops[i](a,b);
Also note: div is a standard function and thus the name is reserved with external linkage or if stdlib.h is included, so you should rename it. :-)
Thank you very much! And if I nested 2 more loops in order to use 3 operators in total, would I need to make 12 functions to avoid rewriting the definition of op? Or can I add more statements such as " int (*op2)(int, int); " to account for the next operation?
@jake_wahle, You do not need to rewrite functions. You can create as many pointers as you like.
|