Finding the Maximum Value in an Array
Learn how to write an algorithm to find the maximum value in an array using Python.
Introduction to Finding the Maximum Value in an Array
To find the maximum value in an array, you can use a simple algorithm that iterates over each element in the array and keeps track of the maximum value found so far.
Step 1: Define the Array
First, define the array that you want to find the maximum value in.
# Define the array
array = [12, 45, 7, 23, 56, 89, 34]
Step 2: Initialize the Maximum Value
Next, initialize the maximum value to the first element in the array.
# Initialize the maximum value
max_value = array[0]
Step 3: Iterate Over the Array
Then, iterate over each element in the array, starting from the second element (index 1).
# Iterate over the array
for i in range(1, len(array)):
# Check if the current element is greater than the maximum value
if array[i] > max_value:
# Update the maximum value
max_value = array[i]
Step 4: Print the Maximum Value
Finally, print the maximum value found in the array.
# Print the maximum value
print("The maximum value in the array is:", max_value)
Example Use Case
Here's the complete code:
def find_max_value():
# Define the array
array = [12, 45, 7, 23, 56, 89, 34]
# Initialize the maximum value
max_value = array[0]
# Iterate over the array
for i in range(1, len(array)):
# Check if the current element is greater than the maximum value
if array[i] > max_value:
# Update the maximum value
max_value = array[i]
# Print the maximum value
print("The maximum value in the array is:", max_value)
# Call the function
find_max_value()
When you run this code, it will output the maximum value in the array.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based algorithms video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked algorithms 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.