share

Thursday, 26 November 2015

How to print numbers from 1 to 10 without using loop?

We can print numbers 1 to 10 or 1 to 100 using recursion. Recursion is a good alternatives of loop. There we can use recursion to print numbers 1 to 10. We also use goto statement but in java we can not used goto statement. visit java keyword list http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html. So we will use here recursion.


package com.javaproficiency;

public class PrintNumber {

public static void main(String[] args) {

printNumberWithRecursion(1);

}

public static void printNumberWithRecursion(int n){

if (n <= 10) {
System.out.println(" number is ="+ n);
printNumberWithRecursion(n+1);
}

}

}


Output :

 number is =1
 number is =2
 number is =3
 number is =4
 number is =5
 number is =6
 number is =7
 number is =8
 number is =9
 number is =10

No comments:

Post a Comment