Determining sum of array elements

Sum of array element is the result of addition of all the element of an array. We can do it using different logic. We will see some most relevant way to determine the sum of array element using C programming.

Sum using function or recursion, pointers as well as loop. Let’s see some C program bellow;

C program to find sum of array elements

// determine sum of array element

#include <stdio.h>

int main(){
    int Num, k, result = 0;
    printf("Enter how many integers of the array : ");
    scanf("%d", &Num);

    int my_array[Num];
    
    printf("Enter all integers of array : \n");

    for(k = 0; k < Num; k++){
        scanf("%d", &my_array[k]);
    }

    for(k = 0; k < Num; k++){
        result += my_array[k];
    }

    printf("\nSum is = %d\n", result);

    return 0;
}

Output of the sum of array program :

sum-of-array-element-in-c-sum-of-all-the-integers-of-array

Sum of array element using pointer in C

// sum of array element using pointer in c

#include<stdio.h>
int main(){
    int sum_array[30], result = 0, j, Num, *ptr;

    printf("Enter how many element in array : ");
    scanf("%d", &Num);

    printf("Enter all element of array : \n");
    
    for(j = 0; j < Num; j++){
      scanf("%d", &sum_array[j]);
    }
    
    ptr = &sum_array;

    for(j = 0; j < Num; j++){
      result = result + *ptr;
      ptr++;
    }

    printf("\nSum of all array element is = %d\n", result);
    
    return 0;
}

Output of program

Enter how many element in array : 7
Enter all element of array :
10 20 30 40 50 60 70

Sum of all array element is = 280

You can write the same logic using function to calculate the sum of array elements. You should do this in your own. However, the logic will be same for other type of data like float, double etc.