Page 395 - Cs_withBlue_J_C11_Flipbook
P. 395
Let us demonstrate direct recursion by printing ‘n’ natural numbers using the recursive method void print(int n).
class Natural
{
void print(int n)
{
if(n>10) // base case
{
System.out.println();
}
else
{
System.out.println(n);
print(n+1); // recursive case
}
}
public static void main() // main method
{
Natural ob = new Natural();
ob.print(1); // method calling
}
}
The output of the preceding program is as follows:
1
2
3
4
5
6
7
8
9
10
13.2.2 Indirect Recursion
Indirect recursion is a coding technique in which the first method calls the second method, which in turn calls the first
method in a circular fashion. It can be demonstrated as:
<return type> function1(parameter)
{
if <base case>
<body if true>
else
function2(parameter)
}
<return type> function2(parameter)
{
if <base case>
<body if true>
393
Recursion 393

