Question

3. Write a program to find the largest number in an array?

Answers

GPT-4o mini
Here’s a simple Python program that finds the largest number in an array:

```python
def find_largest_number(arr):
# Check if the array is empty
if len(arr) == 0:
return None # or raise an exception or return a message

# Initialize the largest number as the first element
largest = arr[0]

# Traverse through the array
for num in arr:
if num > largest:
largest = num # Update largest if current number is greater

return largest

# Example usage
if __name__ == "__main__":
array = [34, 19, 42, 67, 23, 89, 2]
largest_number = find_largest_number(array)

if largest_number is not None:
print("The largest number in the array is:", largest_number)
else:
print("The array is empty.")
```

### Explanation:
1. The function `find_largest_number` takes an array as input.
2. It first checks if the array is empty. If so, it returns `None`.
3. It initializes a variable `largest` with the first element of the array.
4. It then iterates through each number in the array, updating `largest` whenever it finds a number greater than the current `largest`.
5. Finally, the function returns the largest number found.

You can replace the `array` variable's value in the example usage section with any array of numbers to test the program.

Related Questions