Monday, 9 January 2017

Modularity of Code in Java Activity - Recursive Adder Write a recursive method add in a class whose constructor accepts a list of integers as input and the add method returns sum of the list.

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

class RecurseAdder {
    List<Integer> l=new ArrayList<Integer>();
    int index;
    int sum=0;
    public RecurseAdder(List<Integer> l) {
        this.l = l;
        this.index = 0;
    }
    public int add(){
        if(index<l.size()){
       sum=sum+l.get(index);
   index++;
   add();
        }
   return sum;
    }
}
class AddList{
    public static void main(String args[]){

List<Integer> l=new ArrayList<Integer>();
l.add(1);
        l.add(2);
        l.add(3);
        l.add(4);
        l.add(5);
RecurseAdder n=new RecurseAdder(l);
System.out.println(n.add());
    }
}

No comments:

Post a Comment