go to previous page   go to home page   go to next page hear noise

Answer:

The complete program is given below.


Complete Factorial Program

This program is suitable for copying into a program editor, compiling and running in the usual way. Animal brains, such as those in humans, learn best when they see things happen. Run the program. See things happen.


import  java.util.Scanner;

// User enters integer N.  
// The program calculates N factorial.
//
class Factorial
{
  public static void main (String[] args ) 
  {
    Scanner scan = new Scanner( System.in );
    long N, fact = 1; 

    System.out.print( "Enter N: " );
    N = scan.nextLong();

    if ( N >= 0 )
    {
      while ( N > 1 )    
      {
        fact = fact * N;
        N    = N - 1;
      }
      System.out.println( "factorial is " + fact );
    }
    else
    {
      System.out.println("N must be zero or greater");
    }
  }
}

Here are several runs of the program. It is amazing how quickly factorial becomes enormous.

DOS window showing factorial

Warning!   Factorial becomes so big, so fast, that 20! is as large as this program can calculate. However, it will give you an answer for N larger than 20. But the answer will be wrong. This is because when a result requires more bits than a variable has, the variable ends up with garbage. This behavior is called overflow and is a frequent problem with computers.


QUESTION 11:

We don't want the user to see the incorrect result that is calculated when N is larger than 20. How can the program be modified to do this?