Use of For Cycle and Arrays

Asked

Viewed 205 times

0

There are two exercises that I need to solve using a cycle (or loop) FOR... In one of them, I need to catch one array x as a parameter in a function, and multiply all its elements among themselves and return me the result. the other exercise is to write a function in which a number x, as parameter, is computed its factorial (i.e., the multiplication of itself by integers preceding it)... the code I wrote for the array exercise:

function produto (pr) {
  var total = 1;
    for (var i = 0; i < pr.lenght; i++) {
   total = total * pr[i];
}
  return total
}

that of factoring:

function fatorial (x) {
  var fat = 1
for (var i = 0; i <= x; i++){
        fat = fat * x * i;
 }
  return fat;
}

neither of the two work. How can I solve them ?

1 answer

0


The first is just a syntax error: instead of pr.lenght sure would be pr.length

In my example I applied some variable typing patterns. Instead of var, use let for scopes within function.

function produto (pr) {
  let total = 1;
  for (let i = 0; i < pr.length; i++) {
   if(pr[i] === 0)
    continue;
   
   total = total * pr[i];
  }
  return total;
}

console.log(produto([1,2,3,4]))

The second, he is quite wrong the question of logic, I created an example for you to see:

function fatorial (x) {
  let fatorial = 1;
    for (let i = x; i > 0; i--){    
      fatorial = fatorial * i;   
    }
  return fatorial;
}

console.log(fatorial(5))

I believe that the key to the solution lies in the creation of the:

for (let i = x; i > 0; i--){  

my variable i instead of zero, it starts with the value of x, and I continue the loop until it is 1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.