Table of contents
Program
Program to print linearly from 1 to N using recursion in java
package com.getinputs; public class Demo { static void print(int n, int counter) { if (counter > n) { return; } System.out.println(counter); print(n, counter + 1); } public static void main(String[] args) { int counter = 1; int n = 5; print(n, counter); } } Output: 1 2 3 4 5
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 counter (1)
Now we will increment the counter and call the print method with counter = 2 and n = 5 ( recursive call )
2. The recursive print method checks if 2 is greater than 5
Since the condition is false hence if condition will not execute and we will sysout the counter (2)
we will increment the counter and call the print method again with counter = 3 and n = 5 ( recursive call )
3. This will continue till counter = 5
4. As soon as the counter reaches 6, the recursive print method checks if 6 is greater than 5
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 caller print method is the end statement of the function hence all the recursive function complete in 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 1 to N 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.