Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <conio.h>
- /**
- * Recursive programming example
- * @Author: Shaun B
- * @Version: 1.0.0.1
- * @Date: 2012-08-10
- **/
- int main();
- unsigned long factorial(unsigned long);
- unsigned long number = 0;
- char key = 0;
- int main()
- {
- // This line of code might not work with Visual Studio, but it's okay
- // with Code::Blocks -
- system("cls");
- // User prompts:
- printf("This is an example of recursive programming\n");
- printf("Please enter a number between 1 and 12 to \n");
- printf("see its' factorial value,\n");
- printf("or type 0 (zero) to exit.\n");
- printf("C:\\>");
- scanf("%d", &number);
- // Checks for zero to exit:
- if(number == 0)
- {
- return 0;
- }
- // Calls the recursive function factorial, sending the entered number to it:
- printf ("And the answer is %d\nPress enter to start again\nor space and enter to exit.\n",factorial(number));
- // Clears keyboard buffer:
- getchar();
- // Stores next key press into a variable:
- key = getchar();
- // Checks if it's space:
- if(key==32)
- {
- return 0;
- }
- else
- {
- // Restarts the program:
- number = 0;
- main();
- }
- }
- unsigned long factorial(unsigned long n)
- {
- // Break case:
- if (n == 1)
- {
- return n;
- }
- else
- {
- // Calls function recursively:
- return n * factorial ( n-1 );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement