There is error in this program it's not showing the correct output so help me out by modifying it.

#include <stdio.h>
int power(int n1,int n2);
int main()
    int base, exp;
    printf("Enter base number: ");
    printf("Enter power number(positive integer): ");
    printf("%d^%d = %d", base, exp, power(base, exp));
    return 0;
int power(int base,int exp)
    if ( exp!=1 )
        return (base*power(base,exp-1));

Edited by pritaeas: Not a code snippet.

5 Years
Discussion Span
Last Post by Gonbe

I think you missed a part of your function on copy pasting. But your function seems alright except that it doesn't state base cases which results in it not always returning something. (although behaviour is undefined I think.. it might)

Anyway, something like this should fix it:

int power(const int base, const int exp)
    // Base case 1: base^0 = 1.
    // Even though you state positive integers as input, you might as well include 0 so you don't need a case for exp == 1.
    if (exp == 0)
        return 1;

    // Recursive case: base^n = base * base^(n-1)
        return base * power(base, exp - 1);

Edited by Gonbe

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.