Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Program to calculates sum of all elements in a list

Write a program that calculates the sum of all elements in a list.

Program in C

C
#include <stdio.h>

int calculateSum(int arr[], int size) {
    int sum = 0;

    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }

    return sum;
}

int main() {
    int arr[] = {2, 4, 5, 7, 9};
    int size = sizeof(arr) / sizeof(arr[0]);

    int sum = calculateSum(arr, size);
    printf("The sum of all elements in the list is: %d\n", sum);

    return 0;
}

Explanation:

  • In this program, the calculateSum function takes an array arr and its size size as parameters.
  • It initializes a variable sum to 0 and then iterates through each element of the array, adding it to the sum.
  • Finally, it returns the sum.
  • In the main function, an array arr is declared with some example values.
  • The size of the array is calculated using the sizeof operator.
  • Then, the calculateSum function is called with the array and its size, and the sum of all elements is printed to the console.

Output:

Output
The sum of all elements in the list is: 27

Program in Java

Java
public class CalculateSum {
    public static int calculateSum(int[] arr, int size) {
        int sum = 0;

        for (int i = 0; i < size; i++) {
            sum += arr[i];
        }

        return sum;
    }

    public static void main(String[] args) {
        int[] arr = {2, 4, 5, 7, 9};
        int size = arr.length;

        int sum = calculateSum(arr, size);
        System.out.printf("The sum of all elements in the list is: %d\n", sum);
    }
}

Explanation:

  1. The program defines a public class named CalculateSum.
  2. Inside the class, the program defines a static method named calculateSum that takes two parameters: an integer array arr and the size of the array size.
  3. The method initializes a variable sum with an initial value of 0.
  4. It then enters a for loop that iterates from 0 to size – 1.
  5. Inside the loop, each element of the array arr[i] is added to the sum variable using the += operator.
  6. After the loop finishes, the method returns the calculated sum.
  7. The program also defines a main method, which is the entry point of the program.
  8. Inside the main method, an integer array arr is declared and initialized with values {2, 4, 5, 7, 9}.
  9. The size of the array is determined using the length property of the array (int size = arr.length).
  10. The calculateSum method is called with the arr array and its size as arguments, and the result is stored in the sum variable.
  11. Finally, the program uses System.out.printf() to print the result to the console, displaying the message “The sum of all elements in the list is: ” followed by the value of sum.
Output
The sum of all elements in the list is: 27