Java simple recursion

By admin - Last updated: Monday, May 1, 2006 - Save & Share - Leave a Comment
/**
 * @author R
 * 1+2+3+4 .... + 99+100 = 5050
 */

public class Main {
    /** Creates a new instance of Main */
    public Main() {} 

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args)
    {
        System.out.println(recursiveAdd(100));
    }

    public static int recursiveAdd(int upto)
    {
        if(upto == 0)  return 0;
        return upto + recursiveAdd(--upto);
    }
}

Recursion can solve some problems that iteration can not achieve. But recursion is not always the fastest way and efficient, it requires more memory than iteration does in most of the cases.




Posted in Code Notes • Tags: , Top Of Page