You are on page 1of 1

Write a program to print the sum of 5 numbers using recursion.

Take user input


using the Scanner class and save them in an array.
(3 marks)
Input:
Enter 5 elements in an array
2 5 3 6 10
Output:
The sum of the 5 numbers is 26
SOLUTION:
INPUT:
import java.util.Scanner;
public class RecurrsionSum {
static int RecurrsionSum(int arr[], int n)
{
if(n<=0)
{
return 0;
}
return RecurrsionSum(arr, n-1) + arr[n-1];
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter length of array");
int a= sc.nextInt();
int arr[]= new int[a];
System.out.println("Enter 5 elements in an array");
for(int i=0; i<a; i++)
{
arr[i]=sc.nextInt();
}
int sum= RecurrsionSum(arr, a);
System.out.print("The sum of the " + a + " numbers is "+sum);
}
}

You might also like