Advertisement
Shaun_B

Recursively doing factorial mathematics with Java

Aug 13th, 2012
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.util.Scanner;
  2. /**
  3.  * This demonstrates calling methods recursively in a language
  4.  * called Java. It does a factorial calculation.
  5.  * @Author: Shaun B
  6.  * @Version: 2012-08-13
  7.  **/
  8. public class recursive
  9. {
  10.     // Java seems a little more pedantic and it took me a few minutes of
  11.     // actual thinking to convert this from the much easier to understand
  12.     // programming language 'C'.
  13.     private static long number=0;
  14.     private static long returnValue=0;
  15.     // There are probably better ways to read in keyboard inputs, but this
  16.     // works, so...
  17.     private static Scanner keyboardBuffer=new Scanner (System.in);
  18.     // Our main function:
  19.     public static void main (String args[])
  20.     {
  21.         // User prompts:
  22.         System.out.println ("This is an example of recursive programming");
  23.         System.out.println ("Please enter a whole positive number to see");
  24.         System.out.print ("see its' factorial value, ");
  25.         System.out.println ("or type 0 (zero) to exit.");
  26.         System.out.print ("C:\\>");
  27.         number=keyboardBuffer.nextInt();
  28.         // Checks for zero to exit:
  29.         if (number==0)
  30.         {
  31.             System.out.println ("\n\nHave a nice day :-)");
  32.             return;
  33.         }
  34.         // Converts a negative to a positive number (not sure if it'd make any
  35.     // actual difference though...)
  36.         if (number<0)
  37.         {
  38.             number=-number;
  39.         }
  40.         // Calls the recursive function factorial, sending the entered number to it
  41.         // and storing the returned value in the variable returnValue:
  42.         returnValue=factorial (number);
  43.         System.out.format ("And the answer is %d\n",returnValue);
  44.         // Restarts the program:
  45.         number=0;
  46.         returnValue=0;
  47.         recursive.main (null);
  48.     }
  49.     public static long factorial (long n)
  50.     {
  51.         // Break case:
  52.         if (n==1)
  53.         {
  54.             return n;
  55.         }
  56.         else
  57.         {
  58.             // Calls 'method' recursively:
  59.             return n*factorial (n-1);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement