How to use implement a function for integer exponentiation in C

2 Answers

0 votes
#include <stdio.h>

int powInt(const int base, int exp) {
    int result = base;

    for (int i = 1; i < exp; ++i)
        result *= base;

    return result;
}

int main() {
    int x = 5;

    printf("x^3: %d\n", powInt(x, 3));

    return 0;
}




/*
run:

x^3: 125

*/

 



answered May 7, 2021 by avibootz
0 votes
#include <stdio.h>

int powInt(int base, int exp) {
    int result = 1;
    for (;;) {
        if (exp & 1)
            result *= base;
        exp >>= 1;
        if (!exp)
            break;
        base *= base;
    }

    return result;
}

int main() {
    int x = 5;

    printf("x^3: %d\n", powInt(x, 3));

    return 0;
}




/*
run:

x^3: 125

*/

 



answered May 7, 2021 by avibootz
...