Today’s Code Snippet of the Day is a simple Python function to find the largest number in an array:
Code:
def find_largest_number(array):
"""Finds the largest number in an array.
Args:
array: A list of numbers.
Returns:
The largest number in the array.
"""
largest_number = array[0]
for number in array:
if number > largest_number:
largest_number = number
return largest_number
# Example usage:
array = [1, 5, 3, 7, 2]
largest_number = find_largest_number(array)
print(largest_number)
Output:
7
In the above example, we have first defined a function in Python, in which there is a variable named largest_number
is defined which triggers the first element in the array. Then it iterates over the array and compares each element present in the array, If any element is greater than the largest_number
variable, largest_number
variable is updated to that element. Finally, the function returns the largest_number
variable and displays the greatest number present in the array.
Also Read: Reverse a String in Python CSOTD #1
Latest posts by Tanmay Sinha (see all)
- The JS Developer’s Podcast [EP: 1] Introduction to JavaScript - September 27, 2024
- Which is the Best Operating System for Programming? Here are 3 OS to Consider - August 24, 2024
- Top 10 Cybersecurity Threats to Watch Out for in 2024 - August 17, 2024
Pingback: JavaScript Program to Check if a Number is Odd or Even | CSOTD #3 - Mr Programmer