Sum of elements in the Array

Definition & Explanation

This program calculates the sum of all elements in an array. It initializes a variable sum to zero and then iterates through each element of the array, adding each element to the sum variable. After iterating through all elements, the program returns the value of sum, which represents the total sum of elements in the array.

Program Logic

  1. Start
  2. Declare an array arr of integers.
  3. Initialize a variable sum to 0.
  4. Iterate through the array from index 0 to n-1 (where n is the length of the array).
    • Add the value of arr[i] to the sum.
  5. After iterating through all elements, sum will contain the total sum of elements in the array.
  6. Return sum.
  7. End.
C

Method 1 :

#include <stdio.h>

int sumOfElements(int arr[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = sumOfElements(arr, n);
    printf("The sum of elements in the array is: %d\n", sum);
    return 0;
}

Output :

C++

Method 1 :

#include <iostream>
using namespace std;

int sumOfElements(int arr[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = sumOfElements(arr, n);
    cout << "The sum of elements in the array is: " << sum << endl;
    return 0;
}

Output :

JAVA

Method 1 :

public class Main {
    public static int sumOfElements(int[] arr) {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        int sum = sumOfElements(arr);
        System.out.println("The sum of elements in the array is: " + sum);
    }
}

Output :

Python

Method 1 :

a=[10,89,9,56,4,80,8]
sum=0
for i in range(len(a)):
    sum= sum + a[i]
print(sum)

Output :

256