Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

* This is for CS 101 Java class. I can only use \"while\" loops. I cannot use \"

ID: 3724464 • Letter: #

Question

* This is for CS 101 Java class. I can only use "while" loops. I cannot use "for", "do-while" or any other repetition method.*

Write a program that calculates the factorial of a given number. First, it asks for an integer number x between [0 – 13] and calculates its factorial. The program should run until user’s input is an invalid number (outside of interval).

A sample run is shown below:

Please enter a number [0-13]: 0

0! = 1

Please enter a number [0-13]: 5

5! = 120

Please enter a number [0-13]: 2

2! = 2

Please enter a number [0-13]: -1

Goodbye!

This is my code but after the calculation of first factorial it does not work correctly.

import java.util.Scanner;
  
public class Lab04a {
  
public static void main(String[] args) {
  
Scanner in = new Scanner(System.in);
  
//Constants
  
//Variables
int i;
int number;
long factorial;

//Initialize the variables
System.out.println("Please enter a number [0-13]: ");
number = in.nextInt();
i = 1;
factorial = 1;

//Program code
while (0 <= number && number <= 13)
{  
while (number > i)
{
factorial = factorial * number;
number--;
}
System.out.println(number + "! = " + factorial);  
System.out.println("Please enter a number [0-13]: ");   
number = in.nextInt();
}
System.out.println("Invalid number.");   
  
  
  
}
  
  
  
}

Explanation / Answer

// I appreciate your effort. You are just a couple of lines far from getting this done. See highlighted code below.

import java.util.Scanner;
  
public class Main {
  
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
  
//Variables
int i;
int number;
long factorial;

//Initialize the variables
System.out.print("Please enter a number [0-13]: ");
number = in.nextInt();

//Program code
while (0 <= number && number <= 13)
{  
// each time the value of factorial has to be reset because we are working for a different number
factorial = 1;
  
// having a temporary variable for printing purpose
int temp = number;

while (number > 1)
{
factorial = factorial * number;
number--;
}
System.out.println(temp + "! = " + factorial);  
System.out.print("Please enter a number [0-13]: ");   
number = in.nextInt();
}
System.out.println("Goodbye!");   
}
}

/*
SAMPLE OUTPUT
Please enter a number [0-13]: 0
0! = 1
Please enter a number [0-13]: 5
5! = 120
Please enter a number [0-13]: 2
2! = 2
Please enter a number [0-13]: -1
Goodbye!
*/

// Hit the thumbs up if you are happy with it