Reputation:
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;
}
Upvotes: 1
Views: 48
Reputation: 310950
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 );
}
}
Upvotes: 3