Python program that uses the len()
function to print the number of elements present in an array:
def count_elements(arr):
return len(arr)
# Example usage
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(count_elements(arr))
The function count_elements(arr)
takes an array as an argument. It uses the len()
function to find the number of elements present in the array and returns the value.
The example usage creates an array and calls the count_elements()
function to count the elements present in the array and then it prints the count.
You could also use a for loop to iterate over the array, and use a counter variable to count the number of elements in the array
def count_elements(arr):
count = 0
for i in arr:
count += 1
return count
This method uses a for loop to iterate over the elements of the array and a counter variable to count the number of elements in the array. Finally, it returns the count.