In this article we will write a program to print 1 to 10 without loop in java. We can print 1 to n without loop in java by using recursion .Recursion is a good alternatives of loop. We also use goto statement but in java we can not used goto statement. visit Java Keyword List . So we will use here recursion for print 1 to 10 without loop in java
Java Program for print 1 to n without loop
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
In this program we have printed 1 to 10 without loop in java . We can print 1 to 100 without using loop in java by using same logic. Interview ask this question in different ways like print hello 100 times without using loop in java . In this case you need to change following changes in the printNumberWithRecursion() method.
public static void printNumberWithRecursion(int n){
if (n <= 100) {
System.out.println("hello");
printNumberWithRecursion(n+1);
}
}
You can visit more java interview question program for beginners .