11)Python program to print the number of elements present in an array
In this program, we need to count and print the number of elements present in the array.
Some elements present in the array can be found by calculating the length of the array.
1 2 3 4 5
Length of above array is 5. Hence, the number of elements present in the array is 5.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: Calculate the length of the array that is a number of elements present in the array.
-
STEP 3: An in-built function can calculate length.
-
STEP 4: Finally, print the length of the array.
Array in Python is declared as
Arrayname = [ele1, ele2, ele3,....]
len() method returns the length of the array in Python.
#Initialize array
arr = [1, 2, 3, 4, 5];
#Number of elements present in an array can be found using len()
print("Number of elements present in given array: " + str(len(arr)));
12)Python program to print the sum of all elements in an array
In this program, we need to calculate the sum of all the elements of an array. This can be solved by looping through the array and add the value of the element in each iteration to variable sum.
1 2 3 4 5
Sum of all elements of an array is 1 + 2 + 3 + 4 + 5 = 15.
ALGORITHM:
-
STEP 1: Declare and initialize an array.
-
STEP 2: The variable sum will be used to calculate the sum of the elements. Initialize it to 0.
-
STEP 3: Loop through the array and add each element of the array to the variable sum as sum = sum + arr[i].
#Initialize array
arr = [1, 2, 3, 4, 5];
sum = 0;
#Loop through the array to calculate sum of elements
for i in range(0, len(arr)):
sum = sum + arr[i];
print("Sum of all the elements of an array: " + str(sum));