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

Answer:

Change the condition in the if statement so that only integers in the range 0 to 20 are allowed.


Input Testing

Here is the corrected program:

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 && N <= 20 )
    {
      while ( N > 1 )    
      {
        fact = fact * N;
        N    = N - 1;
      }
      System.out.println( "factorial is " + fact );
    }
    else
    {
      System.out.println("N must be between 0 and 20");
      System.out.println("Factorial for N less than 0 is not defined.");
      System.out.println("Factorial for N greater than 20 causes overflow.");
    }
  }
}

QUESTION 12:

This program calculates N! for a very limited range of N. Recall that variables of type double have a much greater range than integer types. Would using variables of type double solve the problem?