factor.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // factor.c -- uses loops and recursion to calculate factorials
  2. #include <stdio.h>
  3. long fact(int n);
  4. long rfact(int n);
  5. int main(void)
  6. {
  7. int num;
  8. printf("This program calculates factorials.\n");
  9. printf("Enter a value in the range 0-12 (q to quit):\n");
  10. while (scanf("%d", &num) == 1)
  11. {
  12. if (num < 0)
  13. printf("No negative numbers, please.\n");
  14. else if (num > 12)
  15. printf("Keep input under 13.\n");
  16. else
  17. {
  18. printf("loop: %d factorial = %ld\n",
  19. num, fact(num));
  20. printf("recursion: %d factorial = %ld\n",
  21. num, rfact(num));
  22. }
  23. printf("Enter a value in the range 0-12 (q to quit):\n");
  24. }
  25. printf("Bye.\n");
  26. return 0;
  27. }
  28. long fact(int n) // loop-based function
  29. {
  30. long ans;
  31. for (ans = 1; n > 1; n--)
  32. ans *= n;
  33. return ans;
  34. }
  35. long rfact(int n) // recursive version
  36. {
  37. long ans;
  38. if (n > 0)
  39. ans= n * rfact(n-1);
  40. else
  41. ans = 1;
  42. return ans;
  43. }