Guest User

Untitled

a guest
Feb 17th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Factorial
  4. int iterativeFactorial(int n) {
  5. int factorial = 1; // why 1 not 0? refer to identity property of multiplication
  6.  
  7. for (; n > 0; n--) {
  8. factorial *= n;
  9. }
  10.  
  11. return factorial;
  12. }
  13.  
  14. int recursiveFactorial(int n) {
  15. if (n < 1) {
  16. return 1;
  17. }
  18.  
  19. return n * recursiveFactorial(n - 1);
  20. }
  21.  
  22. // Positive Multiplication
  23. int iterativeMultiplication(int x, int y) {
  24. int product = 0;
  25.  
  26. for (; y >= 1; y--) {
  27. product += x;
  28. }
  29.  
  30. return product;
  31. }
  32.  
  33. int recursiveMultiplication(int x, int y) {
  34. if (y == 1) {
  35. return x;
  36. }
  37.  
  38. return x + recursiveMultiplication(x, y - 1);
  39. }
  40.  
  41. int main() {
  42. printf("[ITERATIVE ALGORITHMS]\n");
  43. printf("iterativeFactorial(3): %d\n", iterativeFactorial(3));
  44. printf("iterativeFactorial(5): %d\n", iterativeFactorial(5));
  45. printf("iterativeMultiplication(2, 3): %d\n", iterativeMultiplication(2, 3));
  46. printf("iterativeMultiplication(4, 6): %d\n", iterativeMultiplication(4, 6));
  47.  
  48. printf("\n[RECURSIVE ALGORITHMS]\n");
  49. printf("recursiveFactorial(3): %d\n", recursiveFactorial(3));
  50. printf("recursiveFactorial(5): %d\n", recursiveFactorial(5));
  51. printf("recursiveMultiplication(2, 3): %d\n", recursiveMultiplication(2, 3));
  52. printf("recursiveMultiplication(4, 6): %d\n", recursiveMultiplication(4, 6));
  53.  
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment