Advertisement
Guest User

Factorial Program

a guest
Aug 27th, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. /**
  2.  * Calculates and prints out the factorial.
  3.  *
  4.  * @author alu_pahrata
  5.  * @version 8-27
  6.  */
  7. import java.util.Scanner;
  8. public class Factorial
  9. {
  10.     public static void main (String[] args){
  11.     int number = 1, multby = 1, input, counter = 0;
  12.     Scanner scan = new Scanner(System.in);
  13.     System.out.println("Welcome to the Factorial Program!");
  14.     System.out.print("Please enter an integer: ");
  15.     input = scan.nextInt();
  16.     System.out.println("Your number is " + input + "!");
  17.     while (input < 0){
  18.         System.out.println("You have entered in a negative number.");
  19.         System.out.print("Please enter in a positive number: ");
  20.         input = scan.nextInt();
  21.         System.out.println();
  22.     }
  23.     /*
  24.      * This checks to see if a user has entered in 0, if they have in fact entered in 0 then the
  25.      * final calculation that gets printed at the end of the program,
  26.      * which in this case is the variable "number", will be set to 1
  27.      * causing the final output to be "0! = 1
  28.      */
  29.     if (counter == input){
  30.         number = 1;
  31.     }
  32.     /*
  33.      * This while loop checks to see if counter is not equal to input
  34.      * if they are not equal then multby and number are multiplied,
  35.      * after that multby and counter are both increased by one
  36.      * This while loop will keep reapeating untill counter is equal to input
  37.      * This is the factorial algorithm.
  38.      */
  39.     while (counter != input){
  40.         number = multby * number;
  41.         multby++;
  42.         counter++;
  43.     }
  44.     System.out.println(input + "! = " + number);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement