C++ Program to find the sum of array elements using functions and pointers


In this program, You will learn how to find the sum of array elements using functions and pointers in C++.


Sum of array elements using function and pointers

sumOfArray(arr, size, &sum);

Example: How to find the sum of array elements using functions and pointers in C++.

#include<iostream>
using namespace std;

void sumOfArray(int arr[], int n, int *s) {

    for (int i = 0; i < n; i++) {
        *s = *s + arr[i];
    }
}

int main() {

    int arr[10], i, n, s = 0;

    cout << "Enter size of an array:";
    cin>>n;

    cout << "Enter array elements:";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }

    sumOfArray(arr, n, &s);

    cout << "Sum of array elements is: " << s;

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:10 20 30 40 50
Sum of array elements is: 150