I\'m in java one and I need help with this code. please follow the instructions
ID: 3677251 • Letter: I
Question
I'm in java one and I need help with this code. please follow the instructions and help me this program. thank you.
don't answer to this question if you are shubhamarya(your code doesn'twork)
Programming Concepts
1. Arrays
Assignment Description
You will write a program that will calculate an array of factorials and print it out.
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers
less than or equal to n.
For example:
7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040.
3! = 1 * 2 * 3 = 6.
Also, it is a mathematical property that 0! = 1.
To further explain how we calculate factorials for the assignment, note that to find 4!, we can do 4! = 4 * 3 * 2 * 1
Remember that 2! Is 2 * 1. So we can also do 4! = 4 * 3 * (2 * 1)
4! = 4 * 3 * 2!
Also, 3! Is 3 * 2 * 1. But remember that (2 * 1) is also 2!, so 3! can be calculated by doing 3 * 2!.
4! = 4 * 3!
This is true for any factorial. So 7! =7*6!
10! = 10 * 9!
Assignment Requirements
Assume that the user will enter a non-negative integer.
You must use an array that will hold the factorials.
Assignment Suggestions
-Prompt the user to enter the number of factorials to calculate.
-Create a new int array, whose size is the number of factorials to calculate, which was retrieved from the user earlier.
-Assign the first element of the array to 1.
-Loop from 1 to the end of the factorials array
a. Set the current element of the factorials array equal to the element before the current element (current element – 1), multiplied by the counter of the loop.
- Loop from 0 to the end of the factorials array
a. Print the data, like the sample output below.
sample output
user@loki:~$ java Factorial
Enter the number of factorials to calculate: 14
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10!=3628800
11! = 39916800
12!=479001600
13!=6227020800
Explanation / Answer
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
long factArr[] = new long[n+1]; // creating long array instead of int because overflow might happen for
// larger number
factArr[0] = 1; // factorial of 0 is 1
for(int i=1; i<=n; i++){
factArr[i] = i*factArr[i-1]; // fact(i) = i*fact(i-1)
}
// printing
for(int i=0; i<=n; i++){
System.out.println(i+"!="+factArr[i]);
}
}
}
/*
Output:
Enter a number: 10
0!=1
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.