C++ Program to Find Sum of All Elements of Array using Recursion

Write C++ Program to Find Sum of All Elements of Array using Recursion

// CPP Program to Find Sum of All Elements of Array using Recursion

#include <iostream>

using namespace std;

int add_elements(int A[], int start, int n)
{
	static int sum = 0;
	sum = sum + A[start];

	if(start >= (n - 1))
		return sum;

	return add_elements(A, start + 1, n);
}

int main()
{
	int A[] = {17, 18, 91,62, 8, 9, 13};
	int n =  sizeof(A)/sizeof(A[0]);
	int start = 0;

	cout << "Array Elements :--> ";
	for(int i =0; i<n; i++)
        cout << A[i] << " ";

	int result = add_elements(A, start, n);
	cout << "\nSum of Array Elements :--> " << result;
	return 0;

}

Output:

Array Elements :--> 17  18  91  62  8  9  13
Sum of Array Elements :--> 218

≪ Previous | Next ≫