|
| 1 | +#0019 findMinAndMaxNumber (L-B) |
| 2 | + |
| 3 | +## Problem |
| 4 | +Given an array of numbers, find the highest and lowest numbers in the array. |
| 5 | + |
| 6 | +## Test Cases |
| 7 | +- let numbers = [5, 3, 8, 2, 9]; // Min: 2, Max: 9 |
| 8 | +- let numbers = [4, 10, 18, 2, 3]; // Min: 2, Max: 18 |
| 9 | +- let numbers = [0, 100, 8, 21, 39]; // Min: 0, Max: 100 |
| 10 | + |
| 11 | +## Solution |
| 12 | + |
| 13 | +```javascript |
| 14 | +let numbers = [5, 3, 8, 2, 9]; |
| 15 | + |
| 16 | +let min = numbers[0]; |
| 17 | +let max = numbers[0]; |
| 18 | + |
| 19 | +for (let i = 0; i < numbers.length; i++) { |
| 20 | + if (numbers[i] < min) { |
| 21 | + min = numbers[i]; |
| 22 | + } |
| 23 | + if (numbers[i] > max) { |
| 24 | + max = numbers[i]; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +console.log(`Min: ${min}, Max: ${max}`); |
| 29 | +``` |
| 30 | + |
| 31 | +## How it works |
| 32 | +- We start a `for` loop that iterates over each element of the `numbers` array. |
| 33 | +- Inside the loop, we check if the current element is less than the current value of `min`. If it is, we update `min` to the current element. This way, after the loop has finished executing, `min` will hold the smallest value in the numbers array. |
| 34 | +- We also check if the current element is greater than the current value of `max`. If it is, we update `max` to the current element. This way, after the loop has finished executing, `max` will hold the largest value in the `numbers` array. |
| 35 | + |
| 36 | + |
| 37 | +## References |
| 38 | +- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) |
| 39 | +- [Wikipedia](https://en.wikipedia.org/wiki/For_loop) |
| 40 | +- [freeCodeCamp](https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/) |
| 41 | + |
| 42 | + |
| 43 | +## Problem Added By |
| 44 | +- [GitHub](https://github.com/gabrysia97) |
| 45 | + |
| 46 | +## Contributing |
| 47 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 48 | + |
| 49 | +Please make sure to update tests as appropriate. |
0 commit comments