Maybe first idea come to mind to solve this kind of problems is recursive function but also it will be a challenge to write recursive function without any condition.
I tried this approach to print numbers from 10 to 60:
public static void printNumbers(int n){
int divisonByZero = 1 / (61 - n);
System.out.println(n);
printNumbers(n+1);
}
public static void main(String[] args) {
printNumbers(10);
}
But it will crash when it reach number 61
without exception handling
also even with try catch the Arithmetic Exception it's still not a preferable solution because it's handling an exception (runtime error).
I think main problem when using recursive functions is the stop condition.
As well I read that there is a way in C++ by creating a class with a static variable counter and initialize it then increment the counter variable and print it in the constructor after that instantiating number of objects of class counter will print these numbers.
Any suggested solutions to solve this challenge would be appreciated.
You can do something like this: (Idea taken from this answer)
public class Application {
public static void main(String[] args) {
Print40Numbers();
Print10Numbers();
}
private static int currentNumber = 10;
private static void Print1Number() { System.out.println(currentNumber++); }
private static void Print2Numbers() { Print1Number(); Print1Number(); }
private static void Print5Numbers() { Print2Numbers(); Print2Numbers(); Print1Number(); }
private static void Print10Numbers() { Print5Numbers();Print5Numbers();}
private static void Print20Numbers() { Print10Numbers();Print10Numbers();}
private static void Print40Numbers() { Print20Numbers();Print20Numbers();}
}
Based on @Imposter's answer, a reduce version with compacted but readable code
class Sandbox
{
public static void main(String args[]) throws Exception
{
System.out.println(getfalse(10, 60));
}
public static String getfalse(Integer start, Integer stop) throws Exception
{
return
start + "\n" +
Sandbox.class.getMethod("get" + (start == stop), Integer.class, Integer.class)
.invoke(Sandbox.class, start+1, stop);
}
public static String gettrue(Integer start, Integer stop)
{
return "";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With