Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print 1 to 10 without any loop in java [duplicate]

Tags:

java

Possible Duplicate:
Display numbers from 1 to 100 without loops or conditions

Interview question:

Print 1 to 10 without any loop in java.

like image 743
Harry Joy Avatar asked Feb 23 '12 06:02

Harry Joy


1 Answers

Simple way: System.out.println the values:

    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);

Complex way: use recursion

public void recursiveMe(int n) {
    if(n <= 10) {// 10 is the max limit
        System.out.println(n);//print n
        recursiveMe(n+1);//call recursiveMe with n=n+1
    }
}
recursiveMe(1); // call the function with 1.
like image 55
Harry Joy Avatar answered Sep 19 '22 15:09

Harry Joy