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.
Which part is in doubt? Already managed to request the value of n to the user?
– Woss
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++;
#;};
– Galdino
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.
– Galdino
Please [Edit] the question and put all that code in it.
– Woss