/* Computing the sum of n numbers recursively vs. iteratively. Laura Toma csci101 */ public class RecSum { public static void main (String args[]) { int k = 10; //compute the sum of the first k numbers int s = sum(k); System.out.println("Sum of " + k + " numbers is " + s); } // end of main //a recursive method to compute the sum 1 + 2 + .... + k public static int sum (int k) { if (k > 0) return k + sum(k-1); else return 0; } //for comparison, here is an iterative version of sum public static int sumIterative(int k) { int i, s = 0; for (i = 0; i< k; i++) s = s + i; return s; } } // end of class