Finding the Maximum Value in an Array
Learn how to write an algorithm to find the maximum value in an array of integers.
Introduction to Finding the Maximum Value in an Array
This tutorial will guide you through creating a simple algorithm to find the maximum value in an array of integers.
Step 1: Define the Problem and the Approach
We are given an array of integers and we need to find the maximum value in this array. We will use a simple iterative approach to solve this problem.
Step 2: Initialize the Maximum Value
We will initialize the maximum value with the first element of the array. This is because we need to start the comparison from somewhere, and the first element is as good as any.
max_value = array[0]
Step 3: Iterate Through the Array and Update the Maximum Value
We will then iterate through the array, starting from the second element (index 1). For each element, we will check if it is greater than the current maximum value. If it is, we will update the maximum value.
for i in range(1, len(array)):
if array[i] > max_value:
max_value = array[i]
Step 4: Return the Maximum Value
Finally, we will return the maximum value.
return max_value
Example Use Case
Here's an example use case:
array = [12, 45, 7, 23, 56, 89, 34]
max_value = array[0]
for i in range(1, len(array)):
if array[i] > max_value:
max_value = array[i]
print(max_value) # Output: 89
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based arrays video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked arrays books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.