VictoriaTodorova
VictoriaTodorova

Reputation: 11

I am having trouble solving a math problem with while-loop

The math problem says: Write a program in which you can insert a positive number from 1 to 100. When a number outside the range is inserted, there should be an error message and another number should be inserted.

This is the code I tried:

function solve(input) {
  let number = (input.shift());

  while (number < 1 || number > 100) {
    console.log('Invalid number.');
    number = Number(input.shift());
  }
  
  console.log(`The number is: ${number}`)
}

solve(['35', '105', '0', '-200', '77'])

The end result should be:

35
The number is: 35
105
Invalid number!
0
Invalid number!
-200
Invalid number!
77
The number is: 77

Upvotes: 0

Views: 86

Answers (2)

Code Maniac
Code Maniac

Reputation: 37745

Currently it only console.logs The number is: 35 and that's it. ?

It's printing only once because the number < 1 || number > 100 condition fails on first number itself,


Instead what you can do simply is, initialize a counter with value equal to input.length-1, check for value at respective index from input, if that is out of the range show invalid, else just print the number, decrement the counter by 1 each time at end of loop

function solve(input) {
  let i = input.length - 1
  while (i >= 0) {
    if (input[i] < 1 || input[i] > 100) {
      console.log('Invalid number.', `The number is: ${input[i]}`);
    } else {
      console.log(`The number is: ${input[i]}`)
    }
    i--
  }
}
solve(['35', '105', '0', '-200', '77'])

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You need to take all values and check for undefined.

function solve(input) {
    let number = input.shift();

    while (number !== undefined) {
        if (number < 1 || number > 100) {
            console.log('Invalid number.');
        } else {
            console.log(`The number is: ${number}`)
        }
        number = input.shift();
    }
}

solve(['35', '105', '0', '-200', '77'])

Upvotes: 1

Related Questions