The largest number and where it is

Read a list of numbers, and find the largest one and where it is.

What to build

A program that walks through a list and remembers the best item so far.

Requirements

  • Print the largest number and its index, counting from 0.
  • If the largest value appears more than once, give the index of the first one.

Input

One line of whole numbers separated by single spaces.

Output

largest V at index I.

Constraints

There are from 1 to 100 numbers, and they may be negative.

Example

Input:

4 7 9 2

Output:

largest 9 at index 2

Why it works

Starting with the first item, rather than with 0, keeps the answer correct when every number is negative. Using > rather than >= means that a later equal value does not replace the first.

Examples

Example 1 · Input
4 7 9 2
Expected output
largest 9 at index 2
Example 2 · Input
5
Expected output
largest 5 at index 0

Hints

Hint 1

prompt().split(" ").map(Number) turns the line into an array of numbers.

Hint 2

Keep the best value and its index while you loop; start with the item at index 0.

Hint 3

Use > (not >=) so the first of equal largest values wins.

Solution

Show one correct solution (try it yourself first)
const nums = prompt().split(" ").map(Number);
let best = nums[0];
let where = 0;
for (let i = 1; i < nums.length; i++) {
  if (nums[i] > best) {
    best = nums[i];
    where = i;
  }
}
console.log(`largest ${best} at index ${where}`);

Lesson: Arrays →