'How to print the 2nd biggest number without using function and arrays
let biggestNo;
for (let i = 1; i <= 10000; i++) {
const a = prompt("enter a number");
if (!a) {
break;
} else {
biggestNo = Math.max(a);
}
}
console.log(biggestNo);
How do I print 2nd biggest number using this approach without using functions and arrays
Solution 1:[1]
Here's a solution with time complexity of O(n):
const array = [31, 25, 43, 19, 8, 42];
let main = -Infinity, sub = -Infinity;
for (let num of array) {
if(num > main) {
sub = main;
main = num;
} else if(num > sub) {
sub = num;
}
}
console.log('biggest: ' + main);
console.log('second biggest: ' + sub);
Using user input:
let main = -Infinity, sub = -Infinity;
const total = 5;
for(let i = 1; i <= total; i++) {
const num = +prompt(`Enter a number(${i} of ${total}):`)
if(num > main) {
sub = main;
main = num;
} else if(num > sub) {
sub = num;
}
}
console.log('biggest: ' + main);
console.log('second biggest: ' + sub);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
