rec2.c 873 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. /*
  4. * factorials
  5. *
  6. * in both for loop, as well as recursive
  7. * factorial: voor int i, vermenigvuldig dan elke i to je bij 1 komt (uit gaande van positive ints)
  8. *
  9. * dus, f(3)=3*2*1 = 6 ; f(4)=4*3*2*1=24 ; f(a)=no ; f(-2)= no ; f(2.1) = no
  10. *
  11. * will use 2 functions:
  12. * recfac using recursion
  13. * itfac using iteration
  14. *
  15. * should probably figure out how to test this? maybe a dumb K:V?
  16. * * */
  17. int recfact(int input){
  18. int fac = 1;
  19. if (input==1) {
  20. return fac;
  21. }
  22. else {
  23. fac *= input * recfact(input-1);
  24. }
  25. }
  26. int itfact(int input){
  27. int sum = 1;
  28. for (int i = 1; i <= input; i++) {
  29. sum *= i;
  30. }
  31. return sum;
  32. }
  33. int main(){
  34. int input = 5;
  35. //recfact(input);
  36. //itfact(input);
  37. printf("%d\n", recfact(input));
  38. printf("%d\n", itfact(input));
  39. return 0;
  40. }