let arr = [1, 8, 7, 56, 90];
function largest(arr) {
let max = arr[0]; // Initialize max with the first element of the array
for (let i = 1; i < arr.length; i++) { // Start loop from the second element
if (max < arr[i]) {
max = arr[i];
}
}
console.log(max); // Print the largest number
}
largest(arr);
In this corrected version:
max
is initialized with the first element of the array to handle cases where all elements are negative.- The loop starts from the second element since the first one is already used for initialization.
console.log(max)
is used to output the largest number found.
No comments:
Post a Comment