Finding the Maximum Value in an Array
Learn how to write a simple algorithm to find the maximum value in an array of numbers.
Finding the Maximum Value in an Array
Introduction
This tutorial will guide you through creating a simple algorithm to find the maximum value in an array of numbers.
Step 1: Define the Problem
We are given an array of numbers and we need to find the maximum value in this array.
Step 2: Initialize the Maximum Value
We will initialize the maximum value with the first element of the array.
Step 3: Iterate Through the Array
We will iterate through the array starting from the second element and compare each element with the current maximum value.
Step 4: Update the Maximum Value
If we find a value greater than the current maximum value, we will update the maximum value.
Example Code
def find_max(array):
if len(array) == 0:
return None
max_value = array[0]
for i in range(1, len(array)):
if array[i] > max_value:
max_value = array[i]
return max_value
print(find_max([1, 2, 3, 4, 5])) # Output: 5
Conclusion
In this tutorial, we learned how to write a simple algorithm to find the maximum value in an array of numbers.
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.