- 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:
- package com.instanceofjavaTutorial;
- class Demo{
- public static void main(String args[]) {
- System.out.println(1);
- System.out.println(2);
- System.out.println(3);
- System.out.println(4);
- System.out.println(5);
- System.out.println(6);
- System.out.println(7);
- System.out.println(8);
- System.out.println(9);
- System.out.println(10);
- }
- }
Output:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Solution #2
- package com.instanceofjavaTutorial;
- public class Main {
- public static void main(String[] args) {
- printNumbers(1, 10);
- }
- public static void printNumbers(int start, int end) {
- if (start > end) {
- return;
- }
- System.out.println(start);
- printNumbers(start + 1, end);
- }
- }
- 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.
- package com.instanceofjavaTutorial;
- class PrintDemo{
- public static void recursivefun(int n)
- {
- if(n <= 10) {
- System.out.println(n);
- recursivefun(n+1); }
- }
- public static void main(String args[])
- {
- recursivefun(1);
- }
- }
Output:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
No comments