Printing Statements “n” times Without loops
Today, I came across this challenge, and I have tried to solve it. I know this is a beginner level challenge, but just want to post it here. Usually, If we want to print any statements multiple times we tend to use Loops concept. But can you print a statement “n” times without using loops?
Yes, we can do it we can use the Recursive function to print the statements “n” times. Here’s how you do it,
Step 1: You need to define base condition to terminate the recursion after printing “n” times. otherwise, it will cause infinite recursion, leading to a ‘StackOverFlowError’ at runtime.
Step 2: Create a Recursive function to execute the statements.
Below is an example code snippet:
class HelloWorld {
static int n=10; //defined as 10, because I need to print 10 times
public static void main(String[] args) {
printHelloWorld();
}
public static void printHelloWorld(){
System.out.println(“HelloWorld!”);
if(n!=1){
n — ;
printHelloWorld();
}
}
}
Output:
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
HelloWorld!
This is it, let me know if there’s any other way we can do this. Happy Learning!