C Program to Find the Sum of All Elements in an Array

C Program to Find the Sum of All Elements in an Array

#include <stdio.h>

int main() {
    int n, i, sum = 0;

    // Input the number of elements in the array
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int array[n];

    // Input elements in the array
    printf("Enter the elements of the array:\n");
    for(i = 0; i < n; i++) {
        scanf("%d", &array[i]);
    }

    // Calculate the sum of all elements in the array
    for(i = 0; i < n; i++) {
        sum += array[i];
    }

    // Display the sum of the elements
    printf("The sum of all elements in the array is: %d\n", sum);

    return 0;
}

Explanation of the Program:

  • The variables n (number of elements), i (for loop counter), and sum (to store the sum) are declared as integers.
  • The program asks the user for the number of elements in the array using scanf("%d", &n);.
  • int array[n]; creates an array of size n. In this program, the array size is dynamically allocated based on the user input.
  • A for loop is used to input the elements of the array, where the user enters values one by one, stored in array[i].
  • Another for loop runs from index 0 to n-1, adding each element of the array to the sum variable (sum += array[i];).
  • Finally, the program prints the sum of all the array elements using printf().

Program Output

Sample 1:

Input:

Enter the number of elements in the array: 5
Enter the elements of the array:
10
20
30
40
50

Output:

The sum of all elements in the array is: 150

Sample 2:

Input:

Enter the number of elements in the array: 3
Enter the elements of the array:
7
-3
12

Output:

The sum of all elements in the array is: 16
Last updated on