Table of contents
Program
Program to print linearly from N to 1 using recursion in java
package com.getinputs; public class Demo { static void print(int n, int counter) { if (counter > n) { return; } System.out.println(n); print(n - 1, counter); } public static void main(String[] args) { int counter = 1; int n = 5; print(n, counter); } } Output: 5 4 3 2 1
Recursion flow diagram
Explanation
1. The main method calls the print method with counter = 1 and n = 5.
The print method checks if the counter is greater than n.
Checks if 1 is greater than 5. Since the condition is false hence if condition will not execute and we will sysout n (5)
Now we will decrement the value of n by 1 and call the print method with counter = 1 and n = 4 ( recursive call )
2. The recursive print method checks if 1 is greater than 4
Since the condition is false hence if condition will not execute and we will sysout the n (4)
we will decrement the value of n by 1 and call the print method again with counter = 1 and n = 3 ( recursive call )
3. This will continue till n = 1
4. As soon as the n reaches 0, the recursive print method checks if 1 is greater than 0
Since the condition is true hence if condition will execute and it will execute the return statement. The return statement will delegate the pointer to the caller print method
Since the print statement is the end line of the function hence all the recursive functions complete in the below order
recursive call 5 -> recursive call 4 -> recursive call 3 ->
recursive call 2 -> recursive call 1
So this is all about printing linearly from N to 1 using recursion in java. I hope you found this article interesting and valuable. If you are having any concerns or questions about this article please comment below and please share it to help me grow.