Is this code correct to find the max from an array? There are other ways to find the max, however the requirements are to use "for" loop!Thanks! Full reqs : "Create an array with 10 numbers of your choice and a variable named max. Assign 0 to max. In a for loop, find the greatest number, assign it to max and write it in the console."
var numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var max = 0;
var arrLen = numArray.length;
for (i = 0; i < arrLen; i++) {
if (numArray[i] - numArray[arrLen - 1] >= 0) {
max = numArray[i];
} else {
continue;
}
console.log(max);
}
2 Answers 2
Approach it like this:
- Start with
max
at-Infinity
. - Inside the loop body, if
numArray[i]
is greater thanmax
, setmax
tonumArray[i]
. - Show the result after the loop, since while the loop is still running,
max
may not be the maximum value yet.
At the end of the loop, max
will contain the highest value in the array (or -Infinity
if the array is empty).
Don't forget to declare all of your variables, including i
.
-
Thnanks TJ, however requirements are: max= 0; & use a "for" loop. See below: "Create an array with 10 numbers of your choice and a variable named max. Assign 0 to max. In a for loop, find the greatest number, assign it to max and write it in the console." I know about max/ and function to sort the array, however I need to follow reqs. Thoughts? Thanks!Alex Cocan– Alex Cocan2020年03月01日 16:36:33 +00:00Commented Mar 1, 2020 at 16:36
-
@AlexCocan - The suggestion above is following those requirements. (Other than if the requirements really require you to display
max
from within the loop, but I think that's a misreading as it makes no sense to do that...)T.J. Crowder– T.J. Crowder2020年03月01日 17:57:54 +00:00Commented Mar 1, 2020 at 17:57 -
Thanks TJ, I used @ninascholz's solution, that works fine for me.Alex Cocan– Alex Cocan2020年03月01日 20:55:02 +00:00Commented Mar 1, 2020 at 20:55
You could start with the first element as max value and iterate from index one.
Then check and change max if a new maximum is found.
Do not forget to declare all variables (like i
).
var numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
max = numArray[0],
arrLen = numArray.length,
i;
for (i = 1; i < arrLen; i++) {
if (numArray[i] > max) max = numArray[i];
}
console.log(max);
For having all numbers greater than zero, you could omit the assignment with first value and start index from zero.
var numArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
max = 0,
arrLen = numArray.length,
i;
for (i = 0; i < arrLen; i++) {
if (numArray[i] > max) max = numArray[i];
}
console.log(max);
-
Thanks Nina, that works, however reqs are : max = 0; & use "for" loop. Thoughts? Thanks!Alex Cocan– Alex Cocan2020年03月01日 16:41:16 +00:00Commented Mar 1, 2020 at 16:41
Math.max(...numArray)