简体   繁体   中英

Why is my recursion not running with variables?

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;
}

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);
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM