I came up with the solution to this problem to find the two biggest numbers. but it doesn't valid if I input values in increasing orders ex 2, 3 ,4 ,5, 6! what will be the solution for that problem?
let first_biggest_number = 0;
let second_biggest_number = 0;
for (let i = 0; i <= 4; i ) {
let number = Number.parseInt(window.prompt("Enter your number oi"));
if (number > first_biggest_number) {
first_biggest_number = number;
} else {
second_biggest_number = number;
}
}
console.log(first_biggest_number);
console.log(second_biggest_number);
CodePudding user response:
When you replace the biggest number, the old biggest should now be the second biggest.
Then you're not checking whether the number is bigger than the second biggest number before replacing it. So the second number will be the last number that's not biggest.
let first_biggest_number = 0;
let second_biggest_number = 0;
for (let i = 0; i <= 4; i ) {
let number = Number.parseInt(window.prompt("Enter your number oi"));
if (number > first_biggest_number) {
second_biggest_number = first_biggest_number;
first_biggest_number = number;
} else if (number > second_biggest_number) {
second_biggest_number = number;
}
}
console.log(first_biggest_number);
console.log(second_biggest_number);
CodePudding user response:
For such a small number of inputs, just grab them all and sort. You'll write a little less code, and you'll have the ability to get the 3rd biggest or the 5th smallest, and so on.
let numbers = [];
for (let i = 0; i <= 4; i ) {
let number = Number.parseInt(window.prompt("Enter your number oi"));
numbers.push(number); // get all of the input
}
numbers.sort((a, b) => b - a); // rearrange them from large to small
console.log('biggest', numbers[0]);
console.log('next biggest', numbers[1]);
// and you can say console.log('smallest', numbers[numbers.length-1]);
// and so on