Home > other >  How to print the 2nd biggest number without using function and arrays
How to print the 2nd biggest number without using function and arrays

Time:02-05

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

CodePudding user response:

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);

CodePudding user response:

You could use a regular expression to match all numbers collected?

let numbersString;

for (let i = 1; i <= 1000; i  ) {
  const a = prompt("enter a number");
  if (!a) {
    break;
  } else {
    numbersString  = "-"   a
  }
}

const numbers = numbersString.match(/\d /g)
const secondLargest = numbers[numbers.length - 2]

console.log(secondLargest);
  •  Tags:  
  • Related