Sum of Elements in an Array in C++

 


To calculate the sum of elements in an array, you can iterate through each element and add them up. This process can be implemented using a simple loop (like for or while loop).


Example: Sum of Array Elements

Using a For Loop:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements
    int sum = 0;

    // Iterate through the array and add elements to sum
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }

    // Output the result
    cout << "Sum of elements in the array: " << sum << endl;

    return 0;
}

Explanation:

  1. The array arr[] is initialized with 5 elements.
  2. The sum variable is initialized to 0.
  3. A for loop is used to iterate through each element of the array and add it to the sum.
  4. The sum of the elements is printed.

Output:

Sum of elements in the array: 150

Alternative Approach Using While Loop:

#include <iostream>
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements
    int sum = 0;
    int i = 0;

    // Using while loop to sum the elements
    while (i < size) {
        sum += arr[i];
        i++;
    }

    // Output the result
    cout << "Sum of elements in the array: " << sum << endl;

    return 0;
}

Explanation:

  1. The while loop iterates over the array, adding each element to sum.
  2. The result is printed after the loop finishes.

Output:

Sum of elements in the array: 150

Using Standard Library Algorithm (for more advanced use):

You can also use the accumulate function from the <numeric> header to compute the sum of array elements in a more compact way.

#include <iostream>
#include <numeric>  // For accumulate
using namespace std;

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements

    // Using accumulate to find the sum
    int sum = accumulate(arr, arr + size, 0);

    // Output the result
    cout << "Sum of elements in the array: " << sum << endl;

    return 0;
}

Explanation:

  1. accumulate(arr, arr + size, 0) computes the sum of the elements in the array arr[].
  2. The third argument, 0, is the initial value of the sum.

Output:

Sum of elements in the array: 150

Key Points:

  • You can calculate the sum using a loop (for, while) or a more concise method like accumulate.
  • Always ensure to calculate the size of the array when using loops, especially when working with static arrays.
  • accumulate is part of the C++ Standard Library and is a very efficient way of performing accumulation.

Would you like to explore other operations like finding the average or maximum element in the array?

Post a Comment

0 Comments