Find the Largest Number in an Array

Find the Largest Number in an Array | CSOTD #21 min read

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

Tanmay Sinha

Author

  • Tanmay Sinha

    Founder & CEO of MrProgrammer.in | I help Learning Freaks to Step into the World of Programming and Our Mission is to Provide High Quality and Valuable Content to Our Users! We believe that everyone has the potential to learn to code, and we are committed to making that happen. Our courses are designed to be engaging and interactive, and we offer a variety of learning paths to meet the needs of all learners. We are also committed to providing our learners with the support they need to succeed, and we offer a variety of resources to help learners learn at their own pace. If you are interested in learning to code, we encourage you to check out our courses. We are confident that you will find our content to be high-quality, valuable, and makes sense.

One comment

Leave a Reply