•  Basically to display numbers from 1 to 10 or a series we will use for , while or do while loop
  • So here is the programs to do same thing without using loop.
  • This is possible in two ways
  • First one is to display by printing all those things using system.out.println.
  • second one is by using recursive method call lets see these two programs

Solution #1:


  1. package com.instanceofjavaTutorial;
  2.  
  3. class Demo{  
  4.  
  5. public static void main(String args[]) { 

  6.    System.out.println(1);
  7.    System.out.println(2);
  8.    System.out.println(3);
  9.    System.out.println(4);
  10.    System.out.println(5);
  11.    System.out.println(6);
  12.    System.out.println(7);
  13.    System.out.println(8);
  14.    System.out.println(9);
  15.    System.out.println(10);
  16.  
  17. }

  18. }

Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10



Solution #2


  1. package com.instanceofjavaTutorial; 
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         printNumbers(1, 10);
  5.     }

  6.     public static void printNumbers(int start, int end) {
  7.         if (start > end) {
  8.             return;
  9.         }
  10.         System.out.println(start);
  11.         printNumbers(start + 1, end);
  12.     }
  13. }
  • This uses recursion to achieve the same result. In this example, the method printNumbers is called with the start and end numbers as arguments. Inside the method, it checks if the start number is greater than the end number and if so, it returns (ends the recursion). 
  • If not, it prints the current start number and then calls the printNumbers method again with the start number incremented by 1. 
  • This continues until the start number is greater than the end number and the recursion ends.
  1. package com.instanceofjavaTutorial; 
  2. class PrintDemo{
  3.  
  4. public static void recursivefun(int n) 
  5.  
  6.   if(n <= 10) {
  7.  
  8.        System.out.println(n); 
  9.          recursivefun(n+1);   }
  10. }
  11.  
  12. public static void main(String args[]) 
  13. {
  14.  
  15. recursivefun(1); 
  16.  
  17.  }
  18.  
  19. }




Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Instance Of Java

We are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu