Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- // Factorial
- int iterativeFactorial(int n) {
- int factorial = 1; // why 1 not 0? refer to identity property of multiplication
- for (; n > 0; n--) {
- factorial *= n;
- }
- return factorial;
- }
- int recursiveFactorial(int n) {
- if (n < 1) {
- return 1;
- }
- return n * recursiveFactorial(n - 1);
- }
- // Positive Multiplication
- int iterativeMultiplication(int x, int y) {
- int product = 0;
- for (; y >= 1; y--) {
- product += x;
- }
- return product;
- }
- int recursiveMultiplication(int x, int y) {
- if (y == 1) {
- return x;
- }
- return x + recursiveMultiplication(x, y - 1);
- }
- int main() {
- printf("[ITERATIVE ALGORITHMS]\n");
- printf("iterativeFactorial(3): %d\n", iterativeFactorial(3));
- printf("iterativeFactorial(5): %d\n", iterativeFactorial(5));
- printf("iterativeMultiplication(2, 3): %d\n", iterativeMultiplication(2, 3));
- printf("iterativeMultiplication(4, 6): %d\n", iterativeMultiplication(4, 6));
- printf("\n[RECURSIVE ALGORITHMS]\n");
- printf("recursiveFactorial(3): %d\n", recursiveFactorial(3));
- printf("recursiveFactorial(5): %d\n", recursiveFactorial(5));
- printf("recursiveMultiplication(2, 3): %d\n", recursiveMultiplication(2, 3));
- printf("recursiveMultiplication(4, 6): %d\n", recursiveMultiplication(4, 6));
- return 0;
- }
Add Comment
Please, Sign In to add comment