Calculate the Sum of the Elements in an Array

sum of array elements

Programs to calculate the sum of the elements in an array have been shown here. The following section also covers the algorithm, pseudocode and time complexity of the program.






1. Algorithm to calculate the sum of the elements in an array


1. Take input of an array A[] and the size n

2. Set i = 0 and sum = 0

3. Perform sum = sum + A[i]

4. Perform i = i + 1.

5. If i < n, go to step 3 else display sum as the result.





2. Pseudocode to calculate the sum of the elements in an array


Input: An array $A[~]$ and size of array $n$

Output: Sum of the elements in $A[~]$

1. Procedure arraySum($A[~]$, $n$):

2. $sum \leftarrow 0$

3. Repeat for $i \in [0, n - 1]$:

4. $sum = sum + A[i]$:

5. Return $sum$

6. End Procedure





3. Time complexity to calculate the sum of the elements in an array


Time Complexity: O(n)

Where n is the total no of elements in the array.





4. C Program & output to calculate the sum of the elements in an array using iteration

Code has been copied
/*******************************
    alphabetacoder.com
C program to calculate the sum 
of the elements using iteration
*********************************/

#include <stdio.h>

int main() {
    // declare an array
    int arr[5] = {10, 20, 30, 40, 50};
    // declare variables
    int i, sum;

    // initialize variable
    sum = 0;

    // add an element to sum in each iteration
    for (i = 0; i < 5; i++) {
        sum = sum + arr[i];
    }

    // display result
    printf("Total sum = %d", sum);

    return 0;
}

Output


Total sum = 150




5. C Program & output to calculate the sum of the elements in an array using recursion

Code has been copied
/*******************************
    alphabetacoder.com
C program to calculate the sum 
of the elements using recursion
*********************************/

#include <stdio.h>

// recursive function to find
// sum of elements in array
int find_sum(int arr[], int sum, int i){
    // exit condition
    if(i < 0)
	return sum;
    // add current element to sum
    sum = sum + arr[i];
    // call function
    return find_sum(arr, sum, i - 1);
}

int main(){
    // declare an array
    int arr[5] = {15, 25, 35, 45, 55};
    // declare variables
    int min, length, sum;
    
    // calculate size of array
    length = sizeof(arr)/sizeof(arr[0]);
	
    // initialize variable
    sum = 0;
	    
    // call function to get the 
    // sum of elements as return value
    // pass the array, sum = 0 and the
    // size of the array
    sum = find_sum(arr, 0, length - 1);
    
    
    // display result
    printf("Total sum = %d", sum);
     
    return 0;
}

Output


Total sum = 150




No comments:

Post a Comment

If you have any doubts or suggestions, please leave a note.