-5

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.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Have you tried using a `for` loop? – Crowman Sep 14 '13 at 01:46
  • 4
    Welcome to Stack Overflow. Please read the [About] page soon. Ideally you should submit compilable code in the form of an SSCCE ([Short, Self-Contained, Correct Example](http://sscce.org/)). Yes, a loop of some sort makes sense. There's the easy way and the harder way, too. – Jonathan Leffler Sep 14 '13 at 01:48
  • The Weekend - Homework time! – Ed Heal Sep 14 '13 at 01:54
  • 2
    It's also traditional to enclose a function body in braces. – Crowman Sep 14 '13 at 01:55
  • `a^n` already has a meaning in C; `^` is the bitwise exclusive-or operator. I've updated your title to use `a**n`, which is less ambiguous. (C has no exponentiation operator.) BTW, you should also think about how to handle `0**0` and `n < 0`. – Keith Thompson Sep 14 '13 at 02:04

1 Answers1

0

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;
}
csnate
  • 1,601
  • 4
  • 19
  • 31