Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit dc7a255

Browse files
committed
recursion demo 3
1 parent 354f2f9 commit dc7a255

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/binod/RecursionDemo3.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package binod;
2+
public class RecursionDemo3 {
3+
//Q. print sum of first n natural numbers
4+
public static void main(String[] args) {
5+
printNumbers( 5,0);
6+
}
7+
public static void printNumbers( int n, int sum ) {
8+
if ( n==0) {
9+
System.out.println(sum);
10+
return;
11+
}
12+
sum+=n;
13+
printNumbers( n-1, sum);
14+
//control down flow, clearing memory
15+
System.out.println(n);
16+
}
17+
}

0 commit comments

Comments
 (0)