repeat loop - while

Asked

Viewed 55 times

-3

Hey, guys! All right? I’m not able to develop an algorithm in Javascript that "Ask the user to enter a number n and add all numbers from 1 to n" using while only. Would anyone like to help? Tks

const input = require('readline-sync');

let n = Number(input.question('Informe um numero: '));

let cont = 0;

while (cont <= n) {
  let soma = 1 + cont;

  console.log(soma);

  cont++;
};
  • Which part is in doubt? Already managed to request the value of n to the user?

  • const input = require('readline-Sync'); Let n = Number(input.Question('Enter a number: ')); Let cont = 0; while (cont <= n) { Let soma = 1 + cont; console.log(sum); cont++;&#Xa#;};

  • I cannot add from 1 until the same number is typed by the user and print this sum. for example: if the user type 5, the code should display 15, since 1 +2 +3 +4 +5 = 15.

  • Please [Edit] the question and put all that code in it.

1 answer

-2


One simple way to solve this problem is by using the while loop. Value n must be read. This value being a valid integer, we must consecutively add values from 1 to value n.

An imperative approach

const n = parseInt(prompt('Digite um número'))
let inicio = 1
let soma = 0

while (inicio <= n) {
    soma += inicio
    inicio += 1
}

A recursive approach

somarNumeros = (n) => {
    if (n <= 1){
        return 1
    } else {
        return n + somarNumeros(n-1)
    }
}

const n = parseInt(prompt('Digite um número'))

const soma = somarNumeros(n)
console.log(soma)

In this recursive approach we are using a stop condition in case n is less than or equal to 1, so if the user type a negative value we prevent an infinite loop in the execution of the recursion. For an input value for example -5 the calculated value of the function will always be 1.

  • Thank you so much for your help!

Browser other questions tagged

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