Advertisement
Shaun_B

Recursive function call example

Aug 10th, 2012
434
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <conio.h>
  4. /**
  5.  * Recursive programming example
  6.  * @Author:     Shaun B
  7.  * @Version:    1.0.0.1
  8.  * @Date:       2012-08-10
  9.  **/
  10. int main();
  11. unsigned long factorial(unsigned long);
  12. unsigned long number = 0;
  13. char key = 0;
  14. int main()
  15. {
  16.     // This line of code might not work with Visual Studio, but it's okay
  17.     // with Code::Blocks -
  18.     system("cls");
  19.     // User prompts:
  20.     printf("This is an example of recursive programming\n");
  21.     printf("Please enter a number between 1 and 12 to \n");
  22.     printf("see its' factorial value,\n");
  23.     printf("or type 0 (zero) to exit.\n");
  24.     printf("C:\\>");
  25.     scanf("%d", &number);
  26.     // Checks for zero to exit:
  27.     if(number == 0)
  28.     {
  29.         return 0;
  30.     }
  31.     // Calls the recursive function factorial, sending the entered number to it:
  32.     printf ("And the answer is %d\nPress enter to start again\nor space and enter to exit.\n",factorial(number));
  33.     // Clears keyboard buffer:
  34.     getchar();
  35.     // Stores next key press into a variable:
  36.     key = getchar();
  37.     // Checks if it's space:
  38.     if(key==32)
  39.     {
  40.         return 0;
  41.     }
  42.     else
  43.     {
  44.         // Restarts the program:
  45.         number = 0;
  46.         main();
  47.     }
  48. }
  49. unsigned long factorial(unsigned long n)
  50. {
  51.     // Break case:
  52.     if (n == 1)
  53.     {
  54.         return n;
  55.     }
  56.     else
  57.     {
  58.         // Calls function recursively:
  59.         return n * factorial ( n-1 );
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement