Skip to content

Instantly share code, notes, and snippets.

@agaro1121
Last active April 19, 2016 00:11
Show Gist options
  • Save agaro1121/22c10e448dbbacb3497dcc4041d59e15 to your computer and use it in GitHub Desktop.
Save agaro1121/22c10e448dbbacb3497dcc4041d59e15 to your computer and use it in GitHub Desktop.
/**
 * Created by Hierro on 4/18/16.
 */
public class Recursion {
    public static void main(String[] args) {
        int[] array = {1,2,3};

        int sum = getSum(array);
        int sum2 = getSum2(array);

        System.out.println(sum);
        System.out.println(sum2);
    }

    

    public static int getSum(int[] array){
        return getSumHelper(array, array.length, 0);
    }
    private static int getSumHelper(int[] array, int index, int acc){
        if(index == 0){
            return acc;
        }else{
            return getSumHelper(array,--index,acc + array[index]);
        }
    }


    public static int getSum2(int[] array){
        return getSumHelper2(array, 0, 0);
    }
    private static int getSumHelper2(int[] array, int acc, int index){
        if(index == array.length){
            return acc;
        }else{
            return getSumHelper2(array,acc + array[index],++index);
        }
    }


}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment