Python Program to Find Smallest Number in an Array
# Function to find the smallest element in an array
def find_smallest(arr):
# Check if the array is empty
if not arr:
return None # Return None if the array is empty
# Assume the first element is the smallest
smallest = arr[0]
# Iterate through the array
for num in arr:
# Update the smallest if the current element is smaller
if num < smallest:
smallest = num
# Return the smallest element
return smallest
# Initialize an empty array to store user input
user_array = []
# Loop to get user input
while True:
# Get user input for the array element
user_input = input("Enter an element (or 'done' to finish): ")
# Check if the user wants to stop entering elements
if user_input.lower() == 'done':
break
# Convert the input to an integer and add it to the array
try:
element = int(user_input)
user_array.append(element)
except ValueError:
print("Invalid input. Please enter a valid integer or 'done' to finish.")
# Call the function with the user input array and print the result
result = find_smallest(user_array)
if result is not None:
print(f"The smallest element in the array {user_array} is: {result}")
else:
print("The array is empty.")
Output:
Enter an element (or 'done' to finish): 4
Enter an element (or 'done' to finish): 10
Enter an element (or 'done' to finish): 43
Enter an element (or 'done' to finish): 8
Enter an element (or 'done' to finish): 34
Enter an element (or 'done' to finish): done
The smallest element in the array [4, 10, 43, 8, 34] is: 4