In: Computer Science
There are two parts to this activity. Before you write a Java program for this activity, write the pseudocode for this program. Turn in the pseudo code and Java program.
Create a program that prompts the user for an integer number. The program returns the factorial of the number. 0! = 1
In your program, answer the following question: What kind of loop are you using for this example? Counter-controlled loop or sentinel controlled loop? Explain.
Sample Input Enter a number: 8 Sample Output 8! = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 40320
Sample Input Enter a number: 3 Sample Output 3! = 3 * 2 * 1 = 6
Sample Input Enter a number: 10 Sample Output 10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800
Sample Input Enter a number: 0 Sample Output 0! = 1
Sample Input Enter a number: 5 Sample Output 5! = 5 * 4 * 3 * 2 * 1 = 120
Pseudocode
Code
import java.util.Scanner;
public class fact {
public static void main(String[] args)
{
int n;
System.out.print("Enter a number: ");
Scanner in = new Scanner(System.in);
n =in.nextInt();
System.out.print(n+"!=");
int fact=1;
for(int i=n;i>0;i--)
{
if(i==n)
System.out.print(n);
else
System.out.print("*"+i);
fact=fact*i;
}
if(n==0)
System.out.print(fact);
else
System.out.print("="+fact);
}
}
Loop:
counter controlled loop is being used here. Counter controlled loop is nothing but number of iterations already known. here its obvious that the iteration have to done n times.If n is 7 iteration will occur 7 times.
Terminal work
.