exercise on pointers

0

Implements the void power_ref(int* x, int y) function that calculates the power of x leading to y . The result should be placed in the address indicated in the first parameter, changing its initial value.

I have something like this:

#include <stdio.h> 

void power_ref(int* x,  int y){

    int result = (int) *x ^ y;
    *x  = result;
    printf("result: %d", result);
}
    
asked by anonymous 30.09.2017 / 21:55

1 answer

0

Solution # 1:

void power_ref( int * x, int y )
{
    int i = 0;
    int n = 1;

    for ( i = 0; i < y; i++ )
        n *= (*x);

    *x = n;
}

Solution # 2:

#include <math.h>

void power_ref( int * x, int y )
{
    *x = pow( *x, y );
}

Solution # 3:

void power_ref( int * x, int y )
{
    int n = 1;
    int b = *x;

    while(y)
    {
        if(y & 1)
            n *= b;
        y >>= 1;
        b *= b;
    }

    *x = n;
}

Test:

#include <stdio.h>

int main( void )
{
    int n = 2;

    power_ref( &n, 16 );

    printf( "%d\n",  n );

    return 0;
}
    
30.09.2017 / 22:56