This is where methods might come in handy. First an outer loop because you’re counting down (from 4
, in this example).
static final int NR = 4; //for example
static void main(String[] args) {
int total = 0;
for (int i = NR; i > 0; i--)
total += calculateFactorial(i); //i += j; is the same as i = i + j;
System.out.println("Answer: " + total);
}
Now it looks way easier, right? The code suddenly became readable. Now for calculateFactorial(int nr)
all we have to do is calculate 4 * 3 * 2 * 1
(for the factorial of 4
, that is):
public static int calculateFactorial(int nr) {
int factorialTotal = 1;
for (int i = nr; i > 0; i--)
factorialTotal *= i; //i *= j; is the same as i = i * j;
return factorialTotal;
}
Methods just made code easy to read and write. I’d suggest you read a book like Clean Code
solved Sum of factorials in Java [closed]