0

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);
} 
Alex Cocan
  • 11
  • 2

2 Answers2

2

Approach it like this:

  1. Start with max at -Infinity.
  2. Inside the loop body, if numArray[i] is greater than max, set max to numArray[i].
  3. 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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 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 Mar 01 '20 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 Mar 01 '20 at 17:57
  • Thanks TJ, I used @ninascholz's solution, that works fine for me. – Alex Cocan Mar 01 '20 at 20:55
2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392