-1

In this Example the function terminates in a strange way, although the values don't change (no base case is reached)

#include<stdio.h>


int power(int a, int b);


int main(){

    int a;
    int b;
    printf(" Enter number: ");
    scanf(" %d",&a);
    printf(" Enter it's power: ");
    scanf( " %d",&b);
    printf("\n\n Result: %d",power(a,b));
}

int power(int a, int b){

    if( b == 0)
    return 1;
    if ( a == 0)
    return 0;
    if ( b == 1)
    return a;
    else return a*(b,a); //shouldn't it be: "else return a*(a,b-1);" , how does this work!
}
  • 1
    What recursion? What input are you using? What are the results and what did you expect? – Lundin Jun 15 '20 at 14:09
  • you should try printing a and b to see whats going on while the functions execute. You arent using any recursion in the code you provided. – c8999c 3f964f64 Jun 15 '20 at 14:27
  • (`b,a)` does not what you think it does. Read about the [comma operator](https://stackoverflow.com/questions/52550/what-does-the-comma-operator-do) – Jabberwocky Jun 15 '20 at 14:34

1 Answers1

1

This function is actually not recursive since it's not calling itself:

else return a*(b,a);

All it's doing is returning a*a. It should be:

else return a*power(a,b-1);
dbush
  • 205,898
  • 23
  • 218
  • 273