Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,152 questions

40,706 answers

573 users

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

Related questions

1 answer 45 views
1 answer 49 views
1 answer 109 views
1 answer 68 views
1 answer 59 views
...