Write a function to compute a**n in C

261 Views Asked by At

Write a function to compute the power an, where n ≥ 0. It should have the following specification and prototype:

Sets *p to the n’th power of a and returns 0, except when n < 0 or p is NULL, in which case it returns -1.

int power(int a, int n, int * p);'

So far, I am here:

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

int power(int a, int n, int *p);
  if ( n < 0 || p == NULL)
return -1;

Should I use a for loop? Or does that not make any sense at all? I don't know how to calculate an any other way than a * a ... * a.

1

There are 1 best solutions below

0
On

Yes, use a for loop. It was not clear to me how you wanted to handle erroneous conditions (p is null or n < 0). The variable 'res' will get overwritten no matter what in this example.

#include <stdio.h>

int power(int a, int n, int *p)
{
        int i;

        *p = 1;
        for(i = 0; i < n; ++i)
                *p *= a;

        return p == NULL || n < 0 ? -1 : 0;
}

int main()
{
        int res;

        power(4, 2, &res);
        printf("%d\n", res);

        return 0;
}