Menu Close

Compute the sum of array of elements using recursion method

Tina is a Bachelor of Computer Applications (BCA) student. During her final year Campus Interview, she has an opportunity to get a job in a software company in Bangalore.  The company provides Five months training period with Rs.30000/month Package. Then it will be incremented to Rs.55000 per month.  At the end of the training, the examination was conducted for all freshers, Tina got a question paper and one of the questions comes under the concept of programming. 

The program was, she has to calculate the sum of an array of elements using RECURSION to Complete One of Her math Problem.

Tina does not know how to get the output for this program using recursion. So you have to help Tina get this job.

Input:
First line indicates the number of elements 
The second line indicates the elements 

Output:
Print the sum of array elements.
#include <stdio.h>
int sum(int arr[],int start, int len);
int main()
{
  int N,i;
  scanf("%d",&N);
  int arr[N];
  for (i=0;i<N;i++)
  scanf ("%d",&arr[i]);
  int sumofarray=0;
  sumofarray=sum(arr,0,N);
  printf("%d\n",sumofarray);
return 0;
}
int sum(int arr[],int start,int len)
{
  if(start<len)
  {
  return arr[start]+sum(arr,start+1,len);
}
else{return 0;}
}


INPUT_1:
10
1 2 3 4 5 6 7 8 9 10

OUTPUT:
55


INPUT_2:
10
11 21 31 41 51 61 71 81 91 101

OUTPUT:
560


INPUT_3:
5
1 2 3 4 5

OUTPUT:
15


INPUT_4:
7
6 5 4 9 4 2 1

OUTPUT:
31


ILLUSTRATION:

Executed using gcc


Morae Q!