Python program that uses a for loop and an initial minimum value to print the smallest element in an array:
def smallest_element(arr):
min_val = arr[0]
for i in arr:
if i < min_val:
min_val = i
return min_val
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(smallest_element(arr))
The function smallest_element(arr)
takes an array as an argument. It uses a for loop to iterate over the elements of the array. The function declares a variable min_val
and assigns the value of the first element of the array to it. Then, it compares each element of the array with the min_val
and if the element is smaller than min_val
, it assigns the element value to min_val
. Finally, it returns the min_val
as the smallest element in the array.
The example usage creates an array and calls the smallest_element()
function to find the smallest element in the array, and then it prints the smallest element.
You could also use the min()
function to find the smallest element in an array, this method is more pythonic and efficient.
def smallest_element(arr):
return min(arr)
This method uses the min()
function to find the smallest element in the array and returns it.