do the multiplication of values using sum operator and while

Asked

Viewed 1,420 times

2

 var  n1 = Number(window.prompt(" digite o primeiro número "));   
 var  n2 = Number(window.prompt(" digite o segundo número ")); 

 var soma;

 var num = 0; 

        while( num < n1)

    {


        var num = n1+n2+n1;




       num++;
    }

 alert(soma);

1 answer

5


If we take 5 x 7, that gives 35, we can see this way:

 7 + 7 + 7 + 7 + 7   n2
└────────┬────────┘ 
         5           n1

Transporting this to an algorithm means we have to add the value n2 (7, in the example) for n1 times (5, in the example).


That can be implemented like this:

var  n1 = Number(window.prompt(" digite o primeiro número "));   
var  n2 = Number(window.prompt(" digite o segundo número ")); 

var soma = 0;
var num = 0; 

while( num < n1 )       // vamos efetuar a soma n1 vezes
{
  var soma = soma + n2; // e, em cada vez, adicionamos n2 ao total
  num++;
}

alert(soma);

See working on CODEPEN.

  • i wanted to do a multiplication using the sum operator, multiply the two input values

  • That’s exactly what the above code does. If you put 7 and 5, it shows 35. If you put 11 and 11 it shows 121, and so on.

Browser other questions tagged

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