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

* 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 users 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."); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!