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.
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.