Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript For Loop alternative to setting initial variable to 1?

I've made a javascript that will give the factorial of all numbers inputted into the array (minus the first number in the array "0" which I had to put there for filler purposes to make the code run correctly)

fact = [0, 4, 2, 5, 3];
factorial = 1;
for (x = 1; x < fact.length; x++) {
for (i = 1; i <= fact[x]; i++) {
 factorial *= i;
 if (fact[x] === i) {
    console.log(fact[x] + "!" + " " + "=" + " " + factorial);
     factorial = 1;
   }
  }
 }``

Everything works correctly here is the console.log:

4! = 24

2! = 2

5! = 120

3! = 6

My question is how can I change variable x and i's initial value to 0 so I can remove my space holder "0" in my array without making everything outputted to 0 because currently if i set my variables to 0 to start and remove the space holder "0" in my array the equation becomes:

factorial *= 0;

which will make everything equal to zero and I don't want that! I am very sorry I am bad at wording my question thanks for the help!

like image 217
Zackary Lundquist Avatar asked May 26 '26 19:05

Zackary Lundquist


1 Answers

jsFiddle Demo

You could replace the inner for loop with a while loop like this:

var fact = [4, 2, 5, 3];
for (x = 0; x < fact.length; x++) {
 var factorial = fact[x];
 var result = 1;
 while( factorial > 0 ){
  result *= factorial--;        
 }
 console.log(fact[x] + "!" + " " + "=" + " " + result);
}
like image 168
Travis J Avatar answered May 28 '26 09:05

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!