Skip to content

Instantly share code, notes, and snippets.

@isauravmanitripathi
Created March 29, 2019 17:40
Show Gist options
  • Save isauravmanitripathi/f1817a16c59333de0814b2643777e40d to your computer and use it in GitHub Desktop.
Save isauravmanitripathi/f1817a16c59333de0814b2643777e40d to your computer and use it in GitHub Desktop.
public class Sum_Recursive {
private String sumString (final int n) {return "sum (" + n +")";}
private int max = 0;
private void printout (final int n, final String s) {
System.out.println( sumString(n));
for (int i = 0 ; i <= max - n; ++i) {System.out.print(" ");}
System.out.print(s);
}
private int sum(final int n) {
System.out.println("call" + sumString(n));
if (n > max) {max = n;}
if (n == 0) {
printout(n, "n == 0, return 0\n");
return 0;
}
else {
printout(n, "n != 0,");
final int x = sum (n - 1);
printout(n, "return" + x + " + " + n + " (" + ( x + n) + ") \n ");
return x + n;
}
}
public static void main (final String [] args) {
final Sum_Recursive obj = new Sum_Recursive();
obj.sum(5);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment