- /**
- * A recursion demo that
adds the numbers 1-5
- *
- * @author TK Rogers
- * @version 10-8-09
- */
- public class RecursionDemoAdd {
-
public static void main ( ) {
-
System.out.println( "final = " + addUp ( 5 ) ) ;
-
// after the recursion runs ^
-
// the final value is returned here ^
- }
-
-
public static int addUp ( int n ) {
-
// This method is recursion because it calls
itself,
- // changes
the value of its argument each time it's called,
- // has a
means of stopping itself.
System.out.println ( n ) ; // Allows us to see what's happening
-
if (n<=1) {
//stops
the recursion
-
return 1 ;
- }
-
return n + addUp ( n-1 ) ;
-
// return 5
+ addUp ( n-1 ) ;
- //
return 4
+ addUp ( n-1 ) ;
- //
return 3
+ addUp ( n-1 ) ;
- //
return 2
+ addUp ( n-1 ) ;
- //
return 1 ;
- //
Each returned value is saved in a stack. When the recursive
- //
method ends, the values in the stack are processed starting
- //
with the last value. In this cast the values are added.
- }
- }