Finding the maximum and minimum values in an array is a fundamental operation in programming, often encountered when analyzing data. In this tutorial, we’ll explore how to accomplish this task using straightforward code examples.
Loading code…
Here’s how the program works:
- We declare an integer array called
numbersand initialize it with some values. - We initialize two variables,
maxandmin, to store the maximum and minimum values, respectively. We assume that the first element in the array is both the maximum and minimum initially. - We use a
forloop to iterate through the array starting from the second element (index1). We skipped the element at index0since we’ve already assumed that the first element is the maximum and minimum. - Inside the loop, we compare each element with the current maximum and minimum values.
- If an element is greater than the current maximum, we update the
maxvariable. - If it’s smaller than the current minimum, we update the
minvariable.
- If an element is greater than the current maximum, we update the
- Finally, we display the maximum and minimum values found in the array.