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: ");
    scanf("%d",&base);
    printf("Enter power number(positive integer): ");
    scanf("%d",&exp);
    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));

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)
    else
    {
        return base * power(base, exp - 1);
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.