print serial number without use of any kind of loop or simply print statement in Java

print serial number without use of any kind of loop

print serial number without use of any kind of loop or simply print statement in Java

In interview or any where it may be a chance to ask you to print serial number without use of any kind of loop or simply using print statement on console without use of any kind of loops or simply print statement then how can we do ? So for that we can done it through go to statement or recursive method, but in the case java go to statement is not used so we can not do this program with it.

So now, first we have to know ,

what is Recursive Method ?

Recursive Method is a method which calls itself.

 

Also Read: How to check strings are anagram or not in java

Also Read: How to check string is Palindrome or Not in java

Also ReadJava program to count number of vowels in a sentence

 

Program to print serial number with the help of Recursive method:

public class SerialNumber {

    public static void main(String[] args) {

        counter(1);

    }

    static void counter(int x) {
        if (x <= 10) {
            System.out.println(x);
            counter(x + 1);
        }
    }

}

Download Program to print serial number through Recursive method,click here.

In above program we can see that the we create a method called “counter” and which takes one integer parameter as an argument. And we call this counter method from main method and pass ‘ 1 ‘ as an argument. Here we want start printing  serial number from 1 to 10 so that’s why I passed ‘ 1 ‘ as an argument. As we all know recursive method call it self so here also counter method call it self and every time it increment the value of x by one. And In Recursive method we put an one condition because if we don’t use any kind of condition it will executes continuously and goes into infinite. So every time we have to put a condition in Recursive method to stop calling itself after certain time.

So I hope now you got the idea to print serial number without use of any kind of loop or simply print statement in Java.

Thank You 🙂

Stay Connected with Place4Java and our FaceBook Page.

Be the first to comment

Leave a Reply

Your email address will not be published.


*