Reputation: 13
System.out.printf( "%5d", method( 12 ) );
System.out.println();
}
public static int method( int 12 ){
if ( No == 1){
return 1;
}
int bob = 2 * method ( 12 - 1 );
return bob;
}
My program can print the binary sequence; but only the last term. ex) N = 12; 2048 But I want my program to print 1 2 4 8 16 32 64 128 256 512 1024 2048. I'm lost
Upvotes: 1
Views: 560
Reputation: 138
In the case you have mentioned, the recursion method doesnot return all values to the main method and hence main wont print the sequence.A recursive function stores all its local variable values in a callstack(it is datastructure used by C,JAVA). So you have either persist the data in the recursive function or print it there itself. Some knowledge about call stack in recursion would help the understanding.Refer this link.
In case you are expecting the sequence till 1024 for an input of 10, edit the the call "count(N) to count(N+1)" in main method since there are 11 numbers including 1024.
Recursion reminds me one fancy thing.Try to google 'Recursion' , you would get Did you mean: recursion clicking which leads to the same search page again leading to an infinite loop of recursion. :)
Upvotes: 0
Reputation: 2300
Include the print statement in the count method just before the return statement
something like this:
public static int count( int n ){
if ( n == 1)
{
System.out.printf( "%15d", 1);
return 1;
}
int nTerms = 2 * count ( n - 1 );
System.out.printf( "%15d", nTerms );
return nTerms;
}
Upvotes: 1