Print numbers 1 to 100 without using for loop


This is the core Java interview program I faced in my interview, every Java programmer must know the answer to this question because may you will face this program in written test also.
We have the ways to print numbers using for loop and while loop but here we are printing numbers using method recursion.

Method Recursion:


In Java method recursion is a process, a method calls itself continuously until condition false.


return type methodName(){
       //execute code here
       //call same method itself
       methodName();
}




Print numbers using method recursion example


public class PrintNumbers {
       public void printNum(int i){
              //execute if condition until false
              if(i<=100){
                     System.out.println(i);
                     i++;
                     //method calls itself
                     printNum(i);
              }
       }
       public static void main(String[] args) {
              PrintNumbers print=new PrintNumbers();
              print.printNum(1);
       }
}


Output:

This program print numbers from 1 to 100 as per our requirement
1
2
3
To
98
99
100

Explanation:



public void printNum(int i){ // i=1,2,...100          
       if(i<=100){             // 1<=100, 2<=100....100<=100
       System.out.println(i);// 1,2,...,100
       i++;                  //  1++,2++,....,99++
       printNum(i);         //  i=2,3...100
       }
}


printNum(i) method calls itself until if condition false, when the condition is false then control exit from the method scope.

    
if(101<=100){  // i=101 then condition false
       System.out.println(i);
       i++;                  
       printNum(i);       
       }


When i=101 then if(101<=100) condition false and control exit from if condition and no choice to call method itself again.

public void printNum(int i){      
if(i<=100)
{
System.out.println(i);
i++;
printNum(i); 
}
printNum(1)
1<=100  true
1
1++
printNum(2)
printNum(2)
2<=100  true
2
2++
printNum(3)
printNum(3)
3<=100  true
3
3++
printNum(4)
printNum(4)
4<=100  true
4
4++
printNum(5)
Continue like this
printNum(100)
100<=100  true
100
100++
printNum(101)
printNum(101)
101<=100  false
End of the program

I hope you guys are clear with this explanation J and if you have any doubts please comment below.




1 comment: