Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Recursive programming demonstration
- * CNIT 315
- * Tyler Philbrick
- * 2017-02-03
- */
- #include <stdio.h>
- /* Function prototypes */
- int factorial(int);
- int fibonacci(int);
- void hanoi(int, char, char, char);
- int main() {
- int sel;
- while (1) {
- printf("\nMenu:\n1: Factorial\n2: Fibonacci\n3: Tower of Hanoi\n");
- printf("4: Exit\nMake a choice: ");
- scanf("%i", &sel);
- fflush(stdin);
- while (sel > 4 || sel < 1) {
- printf("Invalid choice. Try again: ");
- scanf("%i", &sel);
- fflush(stdin);
- }
- /* Factorial */
- if (1 == sel) {
- int fac_n;
- printf("Enter a desired number n for n! (0-12): ");
- scanf("%i", &fac_n);
- while (fac_n > 12 || fac_n < 0) {
- printf("Invalid choice. Try again: ");
- scanf("%i", &fac_n);
- }
- printf("\n%d! = %d\n", fac_n, factorial(fac_n));
- /* Fibonacci */
- } else if (2 == sel) {
- int fib_n;
- printf("Enter a desired number n for F_n (0-46): ");
- scanf("%i", &fib_n);
- while (fib_n > 46 || fib_n < 0) {
- printf("Invalid choice. Try again: ");
- scanf("%i", &fib_n);
- }
- printf("\nF_%d = %d\n", fib_n, fibonacci(fib_n));
- /* Hanoi */
- } else if (3 == sel) {
- int han_l;
- printf("Enter the number of disks for the Towe of Hanoi (1-1000): ");
- scanf("%i", &han_l);
- while (han_l > 1000 || han_l < 1) {
- printf("Invalid choice. Try again: ");
- scanf("%i", &han_l);
- }
- hanoi(han_l, 'A', 'B', 'C');
- } else if (4 == sel) {
- printf("Good bye!\n");
- break;
- } else {
- printf("Invalid choice. Try again.\n");
- }
- }
- return 0;
- }
- /* Return the product of all positive integers less than
- * or equal to n
- */
- int factorial(int n) {
- if(1 >= n) {
- return 1;
- } else {
- return n * factorial(n-1);
- }
- }
- /* Return the n-th term of Fibonacci sequence */
- int fibonacci(int n) {
- if(0 >= n) {
- return 0;
- } else if(1 == n) {
- return 1;
- } else {
- return fibonacci(n-1) + fibonacci(n-2);
- }
- }
- /* Move n discs from peg_a to peg_c. */
- void hanoi(int n, char peg_a, char peg_b, char peg_c) {
- if(1 == n) {
- printf("Move the top disk: peg %c -> peg %c\n", peg_a, peg_c);
- } else {
- hanoi(n-1, peg_a, peg_c, peg_b);
- hanoi(1, peg_a, peg_b, peg_c);
- hanoi(n-1, peg_b, peg_a, peg_c);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement