Print numbers with using recursion and without using recursion and loop in java.

Print numbers with using recursion and without using recursion and loop in java.

I was taking the interview and the thought comes, let's put a question to the interviewee that you have to print numbers from 1 to 10 without using loops in java.

I was waiting for the incredible approaches and logical strategies but not comes then I decided to write a blog on it so that interviewee would get such approaches also.

Let's try it with recursion

private static void printInc(int n) {
//        Expecton [5]  1,2,3,4,5
//        faith [4] 1,2,3,4
//        exp  = faith +n
        if (n == 0) return;
        printInc(n - 1);
        System.out.print(n+" );

    }

output

1 2 3 4 5 6 7 8 9 10 


let's understand the code, recursion is all about faith and expectation. here my faith is to print the number like 1,2,3,4,5 and it will call again and again until n!=0

let's solve it without using recursion and loop. Yes, we can do this with the help of Arrays.fill

private static void printWithoutRecurrsion() {
    Object num[] = new Object[10];
    Arrays.fill(num, new Object() {
        int count = 1;

        @Override
        public String toString() {
            return Integer.toString(count++);
        }
    });
System.out.println(Arrays.toString(num));
}

output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I hope you like this approach, please comment to me if you have any other approach!

credit goes to

https://www.youtube.com/watch?v=5zQcC4tbZ34


要查看或添加评论,请登录

社区洞察

其他会员也浏览了