Add a sequence of numbers

Asked

Viewed 1,734 times

1

I’m trying to make an algorithm here with this statement:

Given an integer n, n>0, and a sequence with n integers, determine the sum of the positive integers of the sequence. For example, for sequence 6 -2 7 0 -5 2 4 your program should write the number 19.

The problem is time to add up. That’s the code I made:

var numero;
var soma;
for (var i = 0; i < 7 ; ) {
   numero=prompt("Entre com o numero: ");
  parseInt(numero);
   while (numero > 0) { 
    soma = soma + numero;
    numero = 0;
 } 
 i++;
}

document.write("A soma dos positivos é: "+soma);

What happens is that the numbers don’t add up and I have no idea how to make them add up.

4 answers

2

The problem is that while It’s going to be infinite. You don’t really need it because you’re inserting numbers one by one and you can just add.

Also note that parseInt(numero); alone does nothing, you have to assign this value to a variable, like numero = parseInt(numero);.

Suggestion:

var numero;
var soma = 0;
for (var i = 0; i < 7; i++) {
  numero = Number(prompt("Entre com o numero: "));
  soma+= numero;
}

document.write("A soma dos positivos é: " + soma);

1

You can use the code below, but I believe you will have trouble explaining it to your instructor.

var soma = (function* () {
  while (true) {
    var numero = prompt("Entre com o numero: ");
    if (numero != null) 
      yield parseInt(numero);
  }
})()

var total = 0;
for (var i = 0; i < 7; i++)
  total += soma.next().value;
  
alert(total);

0

Has two problems:

  1. parseint returns an integer in the specified base

  2. The sum variable needs to be initialized

var numero;
var soma = 0;
for (var i = 0; i < 7 ; ) {
   numero=prompt("Entre com o numero: ");
   numero = parseInt(numero);
   while (numero > 0) { 
    soma = soma + numero;
    numero = 0;
 } 
 i++;
}

document.write("A soma dos positivos é: "+soma);

0

You did not initialize the value of soma, right now! And don’t use while, use if, while will loop infinitely if the number is <= 0;

var numero;
var soma = 0;
for (var i = 0; i < 7 ; ) {
     numero = prompt("Entre com o numero: ");
     if (parseInt(numero) > 0) { 
      soma += parseInt(numero);
      numero = 0;
     } ;
 i++;
};

console.log(soma);

Browser other questions tagged

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