« Print the sum of all elements of the array recursively.
Problem:
Calculate the sum of all elements of the array recursively.
Input Format :
Line 1 : An Integer N i.e. size of array
Line 2 : N integers which are elements of the array, separated by spaces
Output Format :
Print sum of the array
Constraints :
1 <= N <= 10^3
Sample Input 1 :
3
9 8 9
Sample Output 1 :
26
Sample Input 2 :
3
4 2 1
Sample Output 2 :
7
Solution:
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;1314int sum2(int input[], int n)15{16 if (n == 0)17 {18 return 0;19 }20 return (input[0] + sum2(input + 1, n - 1));21}2223int sum(int input[], int n)24{25 if (n == 1)26 {27 return input[0];28 }29 return (input[0] + sum(input + 1, n - 1));30}31int main()32{33 int n;34 cin >> n;3536 int *input = new int[n];3738 for (int i = 0; i < n; i++)39 {40 cin >> input[i];41 }4243 cout << sum(input, n) << endl;44 cout << sum2(input, n) << endl;45 return 0;46}