1

I wanted to ask why the first code functions and the second is not? Both are recursions and should calculate the binomial coefficient when going up the pascal triangel. Thanks.

#include <stdio.h>
#include <stdlib.h>
int rekurs(int n, int k)
{   if((k==0)||(n==0)||(n==k))
    {
        return 1;
    }

    else{ 
      return rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}
int main(int argc, const char *argv[])
{
    int spalte = atoi(argv[1]);
    int zeile= atoi(argv[2]);
    printf("%d,%d",zahlen,rekurs(spalte,zeile));
    return 0;
}



#include <stdio.h>
#include <stdlib.h>
int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}
int main(int argc, const char *argv[])
{
    int spalte = atoi(argv[1]);
    int zeile= atoi(argv[2]);
    printf("%d,%d",zahlen,rekurs(spalte,zeile));
    return 0;
}
3
  • 2
    Your second code does not have return if the if condition is true. Assigning ergebnis in the else case is also pointless. Commented Jan 24, 2023 at 19:14
  • 1
    Remember that local variables are local for the current call only. In the second variant, each time you call rekurs a brand new ergebnis variable will created for that call and for that call only. When the function returns the variable reaches the end of its life-time and it ceases to exist and the value in it is lost. Commented Jan 24, 2023 at 19:19
  • ALWAYS enable your compiler's warnings. (For gcc, I use -Wall -Wextra -pedantic -Werror.) It would have caught your error. Commented Jan 24, 2023 at 19:29

1 Answer 1

3

The second recursive function returns nothing if the expression in the if statement evaluates to true

int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}

At least you need to write

int rekurs(int n, int k)
{ int ergebnis;
  if((k==0)||(n==0)||(n==k))
    {
        ergebnis = 1;
        return ergebnis;
    }

    else{ 
      return ergebnis = rekurs(n-1,k-1)+ rekurs(n-1,k);
   }

}

though using the variable ergebnis is redundant.

Also it seems the arguments of the functions must be non-negative values but the functions do not take this into account.

So it will be better to declare the function like

unsigned long long int rekurs( unsigned int n, unsigned int k )
{   
    if( ( k == 0 ) || ( n == 0 ) || ( n == k ) )
    {
        return 1;
    }
    else
    { 
      return rekurs( n - 1, k - 1 ) + rekurs( n - 1, k );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.