A Python program to perform arithmetic operations on array
In this post i will show you how to perform arithmetic operations on array by using if-else and for loops inside a function.
#Program on addition of elements in a given array.
Output
Sum of the array elements is: 74 |
We can also call the function definition directly without storing the resultant in to any variable and is shown in below:
Output
74 |
Explanation
To add the elements in a given array simply we are defining a function ‘add’ and passed ‘arr’ as a parameter in to it. The ‘return’ statement returns the sum of array elements by using in-built function ‘sum( )’. An empty array is created and is stored in ‘arr’ variable. Append some elements in to it. Now, we call the function definition ‘add(arr)’ and stored in ‘res’ variable and finally we print the result.
Using if-else
#The above same program can also be written by using if-else inside a function.
Output
Sum of array elements: 97 |
Similarly we can also write the programs for subtraction, multiplication and division of array elements using if-else inside a function.
#Program on Subtraction of array elements using if-else inside a function.
Output
Subtraction of array elements: -17 |
#Program on Multiplication of array elements using if-else inside a function.
Output
Multiplication of array elements: 324480 |
#Program on Division of array elements using if-else inside a function.
Output
Division of array elements: 4.8 |
Using for loops:
The following are the programs of addition, subtraction, multiplication and division of array elements by using for loops inside the function:
#Program on addition of array elements using for loops inside a function:
Note:
We initialize result as 1. We traverse array from left to right and multiply elements with result.
Output
Addition of array elements: 22 |
#Program on subtraction of array elements using for loops inside a function:
Output
Subtraction of array elements: -15 |
#Program on multiplication of array elements using for loops inside a function
Output
Multiplication of array elements: 144 |
#Program on Division of array elements using for loops inside a function
Output
Division of array elements: 0.5 |