Sunday, March 27, 2022

Sum Of Array Elements Using Recursive Function

 Compute and returns the sum of all elements in an array using recursion function where array and the size is given as parameter

import java.io.*;
public class ArrayRecursion
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int arr[]=new int[10];
    void accept() throws Exception
    {
          for(int i=0;i<10;i++)
          {
              System.out.print("\nEnter Value: ");
              arr[i]=Integer.parseInt(br.readLine());
            }
            System.out.print("\nValues as follows: ");
            for(int i=0;i<10;i++)
            System.out.print(" "+arr[i]);
           int x=sumArray(arr,9);
           System.out.print("\nSum of all elements in the array: "+x);
        }
           private int sumArray(int arr[], int n)
       {
            if(n<0)
            return 0;
            int s=arr[n];            
            return s+sumArray(arr,--n);            
        }
            
public static void main(String args[])throws Exception
{
    
ArrayRecursion ob=new ArrayRecursion();
    ob.accept();
}
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner