Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print numbers in specific range without using any loop or conditions (Java)

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.

like image 592
Oghli Avatar asked Jun 06 '17 20:06

Oghli


2 Answers

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



}
like image 144
Santiago Salem Avatar answered Nov 07 '22 02:11

Santiago Salem


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 "";
    }
}
like image 45
ToYonos Avatar answered Nov 07 '22 04:11

ToYonos