views:

3751

answers:

36

Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"? We can easily do using recursion but that again has an if condition. Is there a way to do without using "if" as well? Also no repetitive print statements,or a single print statement containing all the numbers from 1 to 100.
A solution in Java is preferable.

+32  A: 

Sure there is:

System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
System.out.println(6);
System.out.println(7);
System.out.println(8);
System.out.println(9);
System.out.println(10);
System.out.println(11);
System.out.println(12);
System.out.println(13);
System.out.println(14);
System.out.println(15);
System.out.println(16);
System.out.println(17);
System.out.println(18);
System.out.println(19);
System.out.println(20);
System.out.println(21);
System.out.println(22);
System.out.println(23);
System.out.println(24);
System.out.println(25);
System.out.println(26);
System.out.println(27);
System.out.println(28);
System.out.println(29);
System.out.println(30);
System.out.println(31);
System.out.println(32);
System.out.println(33);
System.out.println(34);
System.out.println(35);
System.out.println(36);
System.out.println(37);
System.out.println(38);
System.out.println(39);
System.out.println(40);
System.out.println(41);
System.out.println(42);
System.out.println(43);
System.out.println(44);
System.out.println(45);
System.out.println(46);
System.out.println(47);
System.out.println(48);
System.out.println(49);
System.out.println(50);
System.out.println(51);
System.out.println(52);
System.out.println(53);
System.out.println(54);
System.out.println(55);
System.out.println(56);
System.out.println(57);
System.out.println(58);
System.out.println(59);
System.out.println(60);
System.out.println(61);
System.out.println(62);
System.out.println(63);
System.out.println(64);
System.out.println(65);
System.out.println(66);
System.out.println(67);
System.out.println(68);
System.out.println(69);
System.out.println(70);
System.out.println(71);
System.out.println(72);
System.out.println(73);
System.out.println(74);
System.out.println(75);
System.out.println(76);
System.out.println(77);
System.out.println(78);
System.out.println(79);
System.out.println(80);
System.out.println(81);
System.out.println(82);
System.out.println(83);
System.out.println(84);
System.out.println(85);
System.out.println(86);
System.out.println(87);
System.out.println(88);
System.out.println(89);
System.out.println(90);
System.out.println(91);
System.out.println(92);
System.out.println(93);
System.out.println(94);
System.out.println(95);
System.out.println(96);
System.out.println(97);
System.out.println(98);
System.out.println(99);
System.out.println(100);
truppo
+1, best answer EVER!
Rubens Farias
Best. Answer. Ever.
Brabster
Of course I am looking for a different solution rather than repetitive printing.
Harsha
This is very sad, I don't even understand how this get so many votes. That's a typical problem of Stackoverflow imho. Trivial answers to trivial questions lead to MANY upvotes while taking 10 minutes or more to provide a detailed answer with deep explanations and references to a tricky question will bring you nothing (apart from the satisfaction of helping :) ) because many people won't even get it!
Gregory Pakosz
@Pakosz, "bring your sense of humor"
Rubens Farias
No offense to truppo but isn't this also the most obvious answer EVER?
matt b
solution for dummies :-)
SjB
@Ruben I would have prefer you use my first name but you will blame me for my lack of humor again :) This has nothing to do with humor but repetition (blink)
Gregory Pakosz
@Gregory, ;-DDD
Rubens Farias
This doesn't work. Ok, it prints the numbers from 1 to 5, but what with the three dots?
Daniel Daranas
Great explanatory edit. I wish I could upvote it again :D
Daniel Daranas
@Gregory I think this gets most votes because it's a straightforward, but basically useless answer to a stupid, useless question.
Michael Borgwardt
I don't understand why the complaint about this answer got so many upvotes! It is the simplest correct answer to the question asked!
Kevin Bourrillion
It's easy, there's a simple recursive answer using exceptions that avoids the conditionals which is a "better" solution. For a homework solution it neither helps the OP gain a deeper understanding of programming nor does it promote good coding standards. That's why I upvoted Gregory's comment.
wheaties
I don't see how it is a "problem" that this is the most upvoted answer. It's a trivial "but" correct one (as if being trivial was a bad thing), and it doesn't rule out the possiblity of more tricky answers being posted below. True, some people will upvote it just by intertia when they see it is a highly voted one, but this happens all the time and it's hard to avoid - it happened to me with Gregory's comment, indeed.
Daniel Daranas
@Oscar> @truppo can't be blamed for votes casted by others. It's just the voting system that makes us rediscover the bikeshed problem.
Gregory Pakosz
Optimized version: http://stackoverflow.com/questions/2044033/print-numbers-from-1-to-100-in-java-without-using-any-loops-or-conditions/2044291#2044291
OscarRyz
@Gregory: Yeah, but upvotes are meant for helpful answers like this: http://stackoverflow.com/questions/2044033/print-numbers-from-1-to-100-in-java-without-using-any-loops-or-conditions/2044236#2044236 And he knows ( I hope ) his answer wasn't that helpful. He should've mark his answer as CW. But, yes, is not truppo fault, but those who up vote it.
OscarRyz
@Oscar: Why exactly should he have marked his answer as CW? Because "in the end" he was answering to a fundamentally useless question?
Daniel Daranas
This is a perfectly valid answer. Essentially it's precomputing the answer and then outputting it. Precomputing results is a perfectly valid programming technique.
Steve Kuo
This is the only correct answer; every other one is using a loop of some variety (either directly or indirectly).
Noon Silk
+1 The obvious answer is often the best answer.
Stephen Canon
+1 because it's funny as hell and we shouldn't be answering other people's homework anyway--it's strange that so many people miss these two glaring points.
Bill K
Ahhhh, the sarcastic answer! Favored by smart ass-programmers for 50 years.
Ash
I'll defend this answer, it's basically a lookup table and those are perfectly acceptable in many applications.
temp2290
I think a loop was used to create this code lines...
Carlos Heuberger
+1  A: 

Loop unrolling? :-)

Gordon Broom
+29  A: 

Pseudo code. Uses an array to force an exception after 100 elements which is caught and does nothing.

function r(array a, int index){
    a[index] = a[index-1]+1
    print a[index]
    r(a, index+1)
}

try{
    array a;
    a.resize(101)
    r(a, 1)
}catch(OutOfBoundsException){
}

EDIT
Java code:

public void printTo100(){
    int[] array = new int[101];
    try{
        printToArrayLimit(array, 1);
    }catch(ArrayIndexOutOfBoundsException e){
    }
}
public void printToArrayLimit(int[] array, int index){
    array[index] = array[index-1]+1;
    System.out.println(array[index]);
    printToArrayLimit(array, index+1);
}
Yacoby
This one prints numbers from 100 to 1 in descending order. I am just curious that can we somehow print numbers from 1 to 100 in ascending order?
Harsha
Neat answer but I hope to god this isn't what his instructor was hoping for
matt b
a.fill(101) is unecessary, just set a[index]=0 and print index. Of course, this still uses an 'if' statement internally in the JVM...
BlueRaja - Danny Pflughoeft
I was trying something with a labeled block hoping to simulate a goto and then causing an Exception, but it appears that `break`ing out of a labeled block causes the execution to be transfered to the statement _following_ the block :(
Chinmay Kanchi
A recursive loop is still a loop...
Jorn
@BlueRaja technically the JVM probably uses 32,000 if's just to do a single system.out.println("1").
Bill K
@Jorn no it isn't. They are two different things.
Yacoby
Recursion is more like telescoping than looping.
trinithis
A decent compiler should convert tail-recursion into a loop or setjmp/longjmp to avoid blowing your stack. Sun's javac doesn't by default. I believe IBM's does.
KitsuneYMG
@kts This will still work fine even if it is converted into a loop.
Yacoby
A: 

Try :

int i = 1;
System.out.println(i++);
System.out.println(i++);
System.out.println(i++);
....
fastcodejava
This is ridiculous. This exact answer ( almost identically ) was also written and that had +15 votes so far: http://stackoverflow.com/questions/2044033/print-numbers-from-1-to-100-in-java-without-using-any-loops-or-conditions/2044046#2044046
OscarRyz
-1: If you are going to post a solution like this, you should write out the entire thing. As it is, it doesn't even compile.
trinithis
+11  A: 

Yes, it's possible, but it's terrible. There's any number of ways that will use either recursion or nested type creation, with exception handling for flow control. This has no real-world application IMO and should be avoided in real code at all costs.

Here's an example that uses recursive type instantiation with exception handling to control termination. It print the number is descending order, but that would be trivial to change to ascending, by just subtracting 99 (or whatever constant) from the value being printed.

class PrintVal
{
  // called with a list containing as many items as you want, less one...
  public PrintVal( List<int> items )
  {
      System.out.println(items.size()+1);  // print the size of the list
      try { 
        items.remove( items.size()-1 );  // will throw when items is empty
        new PrintVal( items );
      }
      catch( Exception ) { /* swallow and terminate */ }
  }
}

// setup and invocation that performs the output
ArrayList<int> strList = new ArrayList<int>( new int[99] );
PrintVal instance = new PrintVal( strList );  // all output happens here
LBushkin
"subtracting 99 (or whatever constant) from the value being printed." So print value-99. Value is 100, 99, 98... 98. 98-99 = -1.What you want to do is subtract the value being printed from 101.101-value
Wallacoloo
This code is not complete. How do you create the list with 100 items?
Jorn
I thought that would be self explanatory, but I'll add that for completeness.
LBushkin
+19  A: 

Check out the Divide + Conquer answer from the C# thread. It's evil, but brilliant:

http://stackoverflow.com/questions/1810028/how-to-print-1-to-100-without-any-looping-using-c/1810848#1810848

Adam Pope
this way is the most awesome!!!
tooleb
Holy Cow !!!!!!!!!!!!!!!!!!!!!!!
Hamish Grubijan
This method is the only one I've seen so far that solves it without ANY conditional branching and without hard-coding the print. (Though the printLn function uses some form of conditional branching, there's really no way around that)
Wallacoloo
This is pure. I feel icky.
GalacticJello
+2  A: 

Implement a recursive call incrementing and printing the number. Configure your VM to run out of stack after 100 calls. No conditions, no loops. cough ;-)

PartlyCloudy
+3  A: 

without any loop and condition :

public static void recfunc(int a[], int i)
{
    System.out.println(i);
    int s = a[i];
    recfunc(a, i + 1);
}

public static void main(String[] args)
{
    int[] a = new int[100];

    try
    {
        recfunc(a, 1);
    }
    catch (Exception e)
    {

    }
}

with recursion and without if I think use "?" for conditioning :

public static int recfunc(int i)
{
    System.out.println(i);
    return (i < 100) ? recfunc(i + 1) : 0;

}


public static void main(String[] args)
{
    recfunc(1);
}
SjB
That's again a condition-based statement.
PartlyCloudy
Array bounds checking uses conditionals behind the scene.
trinithis
+3  A: 

Abuse an exception to serve as a condition.

public class Main {
    private static int[] stopper = new int[100];

    public static void main(String[] args) {
        try {
            print(1);
        } catch(ArrayIndexOutOfBoundsException e) {
            // abuse of try catch
        }
    }

    private static void print(int i) {
        System.out.println(i);
        stopper[i] = i;
        print(i + 1);
    }
}
Arne
+3  A: 

Here's a hint that be helpful.

The assert statement isn't the forbidden if statement.

S.Lott
Yes but the assertions can be easily disabled on the VM
Greg
While true, it seems to be the point of the homework.
S.Lott
+68  A: 

DO NOT DO THIS UNDER ANY SANE CIRCUMSTANCES!

public class Fail {

    public void thisFails(int x){
        System.out.println(x);
        Integer[] bigArray = new Integer[9450];
        thisFails(x+1);
    }

    public static void main(String[] args) {
        Fail failure = new Fail();
        failure.thisFails(1);
    }
}

When this is ran using 1m of heap space (java -Xmx1m Fail) it will run out of heap at the 100th recursion.

...

I will now go wash my hands.

yx
+1 for pure insanity
Jorn
Wow, congrats on figuring out exactly how much heap space this takes.
Robert Fraser
This uses a loop.
Noon Silk
@silky: I see no loop, it is a recursive call. That is an awesome way IMO
Guvante
Guvante: I shouldn't need to point out how obvious it is that a recursive call is a loop.
Noon Silk
It would do the 32/64-bit thing better if you use `int[]` instead of `Integer[]`. Warmed up, the (dead) reference may be dropped.
Tom Hawtin - tackline
@silky, your reputation is high enough that you should know a loop and a recursive call are different things that can be used to achieve the same result. We can also achieve the same result using only universal logic gates (NAND/NOR) but it doesn't mean a bunch of NOR gates is a loop.
z5h
@silky re-read the question, he says recursion is allowed but unusable due to the stop condition which requires an if; besides - loops and recursions are not the same thing, they can just achieve the same thing in different manners
laura
recursion in this case is just a special way to write a loop... to call or not to call this a loop, is a pure question of vocabulary and language.
+112  A: 

Know your libraries.

public class To100 {
    public static void main(String[] args) {
        String set = new java.util.BitSet() {{ set(1, 100+1); }}.toString();
        System.out.append(set, 1, set.length()-1);
    }
}

(You can use String.replaceAll to change the separator. For instance, .replaceAll(", ", " ") for space separation.)

Explanation:

  • java.util.BitSet is a handy little class that represents an arbitrarily large (non-sparse) set of positive integers. (It does have so bad bits: not final, unnecessarily thread-safe, doesn't support building well, etc.)ta.
  • Extends BitSet allows me to write java.util only once. The JDK7 "diamond operator" should help reduce duplication with generic types, but no help for the more common situation. :(
  • The double braces are the Double Brace idiom - an anonymous inner class containing only an instance initialiser. It is a hack. It increase runtime size, and hence start-up time. Distribution size is negligible if you use pack200.gz. I think the modern world is ready for it. Your colleagues may not be. Perhaps start by using it for test da
  • BitSet.set sets a bit in the set (two completely different meanings of the word "set" there - I like it). It's a half-open range - the top value exclusive; the bottom inclusive. Add 1 to the top to include 100.
  • BitSet.toString is actually precisely defined by the API docs.
  • append was added to PrintStream with the introduction of the Appendable interface in J2SE 5.0. It essentially does a substring and prints the result. (A little secret: this isn't actually guaranteed by the spec to flush the output, but implementations always will.)
  • Starting the append at 1, and taking one off the length strips the braces from the string representation of BitSet.
  • "Know your libraries." Taken from Josh Bloch. See Java Puzzlers, puzzle 94. It really is good to know what is in the libraries. At least know where to look. Save your time, save maintenance time and get it right first time.
Tom Hawtin - tackline
I'd like to upvote this a few more times because other than truppo's ridiculous answer, it is the only one that doesn't use a control structure. Yes, try/catch is a control structure.
iandisme
I would upvote this twice, one for the answer perse, and once of the title.
OscarRyz
I would upvote this, but I have reached my daily limit, give me a few more hours.
Anthony Forloney
Wow. Just, wow.
matt b
I just noticed now that there is use of the double brace initialization! Which is something I found out a few days ago. Amazing.
Anthony Forloney
Can someone explain how does the above code work?
Harsha
It's relying on BitSet's toString() to iterate though all 100 values. While this is clever answer, I think truppo's is more straighforward and understandable.
Steve Kuo
it's a clever solution, although I'd say using a library that uses loops and/or conditionals to do the job might not be in the spirit of the question
Peter Becker
I have to bow down to your knowledge of java classes. I don't think I've ever used a BitSet before...
yx
@Hashsha: Much better, I'll give you the docs: http://java.sun.com/javase/6/docs/api/java/util/BitSet.html#set%28int,%20int%29 http://java.sun.com/javase/6/docs/api/java/util/BitSet.html#toString%28%29
OscarRyz
+12  A: 

Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"?

Using an optimized version of this:

System.out.println("1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 , 44 , 45 , 46 , 47 , 48 , 49 , 50 , 51 , 52 , 53 , 54 , 55 , 56 , 57 , 58 , 59 , 60 , 61 , 62 , 63 , 64 , 65 , 66 , 67 , 68 , 69 , 70 , 71 , 72 , 73 , 74 , 75 , 76 , 77 , 78 , 79 , 80 , 81 , 82 , 83 , 84 , 85 , 86 , 87 , 88 , 89 , 90 , 91 , 92 , 93 , 94 , 95 , 96 , 97 , 98 , 99 , 100"); 

Next question?

OscarRyz
+4  A: 

Another divide and conquer:

public class Print100 {
    public static void main (String...args) {
        Runnable r1 = new Runnable () {
            int n;
            public void run () {
                System.out.println(++n);
            }
        };

        fourTimes(fiveTimes(fiveTimes(r1))).run();
    }

    public static Runnable twice (Runnable a) {
        return add(a,a);
    }

    public static Runnable fourTimes (Runnable a) {
        return twice(twice(a));
    }

    public static Runnable fiveTimes (Runnable a) {
        return add(a,fourTimes(a));
    }

    public static Runnable add (final Runnable a, final Runnable b) {
        return new Runnable () {
            @Override
            public void run () {
                a.run();
                b.run();
            }
        };
    }
}
Pete Kirkham
+6  A: 

let Arrays do the job:

public static void main(String[] args) {
    Object[] numbers = new Object[100];
    Arrays.fill(numbers, new Object() {
        private int count = 0;
        @Override
        public String toString() {
            return Integer.toString(++count);
        }
    });
    System.out.println(Arrays.toString(numbers));
}
Carlos Heuberger
The Java library does not appear to define the order `toString` is called. (`Arrays.asList` vs `Arrays.toString` doesn't seem to be very well defined, but that is another issue.)
Tom Hawtin - tackline
+44  A: 

Is there a way to print numbers from 1 to 100 without using any loops or conditions like "if"?

I can't believe noone suggested this yet:

System.out.println("numbers from 1 to 100 without using any loops or conditions like \"if\"?");
nikie
hehe, +1 but missing part of the text "We can easily do...as well"
Carlos Heuberger
+3  A: 

System.out.println("numbers from 1 to 100")

HAHAAHA! (For those who don't get it, read the question literally... at least as of this writing.)
trinithis
If you have to explain a joke, isn't a joke anymore
Rubens Farias
Considering the question didn't specify *integers*, I would have to say that this is the only correct one I've seen so far!
Ken
+3  A: 

If try and catch are legal I would think it would be easy and fairly clean to recurse and then just divide by zero when you're done. Besides all that it always rocks when you get to divide by zero both for fun and profit.

public class Main {
public static void main(String[] args) {
  count(100);
}
private static int count(int x) {
   try {
      int value=1/x;
      count(x-1);
      System.out.println(x);
   }
   catch (Exception e){
      return 0;
   }
   return 1;
}
stilljb
+6  A: 

Here is one using a thread (I inflated the sleep time to account for fluctuations in system speed). I couldn't think of a way to get rid of the try / catch:

public class Counter extends Thread{

    private int cnt;

    public Counter(){
        this.cnt = 0;
    }

    private void increment(){
        System.out.println(cnt++);
        try{
            Thread.sleep(1000);
        }catch(Exception e){}
        increment();
    }

    public void run(){
        increment();
    }

    public static void main(String[] args) throws Exception{
        Counter cntr = new Counter();
        cntr.start();
        cntr.join(100000);
        cntr.interrupt();
        System.exit(0);
    }

}
jckdnk111
he doesn't want to use something as simple as a loop, and you suggest a THREAD???
Coleman
AMAZING!!!!!!!!
trinithis
+14  A: 

download from pastebin

System.out.println((new URL("http://pastebin.com/pastebin.php?dl=f722c7eb0")).getContent())
Jimmy
+1  A: 

//Descending Order

 class Test
    {

      int count = 101;

      public void printNo()
      {
        try
        {
          count = count--;
          int nw = count/count; // to prevent printing zero
          int[] array = new int[count];
          System.out.println(array.length);
          printNo();
        }
        catch(Exception e)
        {
          System.out.println("DONE PRINTING");
        }
      }

      public static void main(String[] args)
      {
        Test objTest = new Test();
        objTest.printNo();


      }
    }
Zaje
wouldn't I got a zero? (easy to change...)
Carlos Heuberger
+3  A: 

I'm a .Net developer but I would guess there's a Java equivalent of this...

static int i = 1;
static System.Timers.Timer timer = new System.Timers.Timer();

static void Main(string[] args)
{            
    timer.Interval = 10;  //milliseconds
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    timer.Enabled = true;
    timer.Start();

    //let the timer complete... (3000 to show the output stops)
    System.Threading.Thread.CurrentThread.Join(3000);
}

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Console.WriteLine(i++);
    timer.Enabled = (i < 101);   
}
Austin Salonen
Though this may not comply with the no-conditionals rule because you are simply pushing those checks to a class where they're actually hidden. If you read the rule as "I don't use any conditions or loops," using a timer to do them for you becomes valid.
Austin Salonen
+2  A: 

This reminds me of programming my TI-55 years and years ago. It had 32 programmable instruction steps, and a RESET instruction that would jump to instruction zero, so simple looping could be implemented. The problem was getting it to stop, which boiled down to getting it to do an operation that caused an error, e.g., divide by zero.

Thus:

public static void main(String[] args)
{
    printN(100);
}

private static void printN(int n)
{
    try
    {
        int  t = 1/n;    // Exception when n is 0
        printN(n-1);     // Recurse, down to 0
        System.out.println(n);
    }
    catch (Exception ex)
    {
        // Stop recursing
    }
}

Note: Yes, I know this is similar to @Yacoby's solution.

Loadmaster
+9  A: 

Or if you like to use reflection :-)

public class Print100 {

    public static void emit0(int index) throws Exception {
        System.out.println(index);

        String next = new StringBuilder()
                          .append("emit")
                          .append(index / 100)
                          .toString();

        Print100.class.getMethod(next, Integer.TYPE)
                          .invoke(null, index+1);
    }

    public static void emit1(int index) {

    }

    public static void main(String[] args) throws Exception {
        emit0(1);
    }

}
Mike
Wow... uh... awesome.
Robert Fraser
Nice one, although I don't think you need to print 0 and also note that StringBuilder is overkill here.
CurtainDog
+1  A: 

This example uses no conditions and no exceptions.
(There is a kind of hidden condition in the short-circuit OR).
Loops are avoided by using recursion.

public class OneToHundered {

  public static boolean exit() {
    System.exit(0);
    return true;
  }

  public static boolean printToHundered(int i) {
    boolean r;
    System.out.println(i);
    r = (i<100) || exit();
    printToHundered(i+1);
    return r;
  }

  public static void main(String[] args) {
    printToHundered(1);
  }
}
Curd
This uses short circuit OR. I would prefer something without using any sort of conditional expressions.
Harsha
@Harsha: have a look at my second posting
Curd
+1  A: 

Does it have to be Java? If ruby's allowed:

puts [*1..100].join("\n")

I'd like to see anything this concise in Java.

Andrew Grimm
I guess this can be accomplished easily in a low level language but sort of becomes tricky to do it using a high level language like java. Hence I would prefer a java solution.
Harsha
Isn't ruby a higher level language than Java?
Andrew Grimm
I was under the impression that Ruby is a lightly typed language like Python and Java is a strongly typed language.I also think that languages like Ruby which are lightly typed are more concise than Java . Hence I was trying to find a solution using Java. I think I would be wrong to say that Ruby isn't a higher level language than Java.
Harsha
@Harsha: You've mixed up high-level and low-level languages. Assembly is low-level, C is slightly higher, Java even higher and Ruby/Python etc are more or less the highest-level.
Chinmay Kanchi
Ruby/Python are not higher level than Haskell. Here's a Haskell solution for kicks: `mapM print [1..100]`.
trinithis
Making the Java vs Ruby argument is comparing apples to oranges.
gpampara
Ruby is as strongly typed as Java. The difference is that Java is statically typed; Ruby dynamically typed.
Wayne Conrad
"I'd like to see anything this concise in Java." Why? The IDE writes 99% of the code for you in Java. Anyway, you can do similar code in Groovy.
Yar
+5  A: 

My solution without verbosity. It doesn't use any control structure other than function application. It also doesn't use library code to help out. My code is easily extensible to print out the range [a, b]. Just change conts [n / 100] to conts [(n - a) / (b - a)] and of course change new Printable (1) to new Printable (a).

To100.java:

class Printable {
  private static final Continuation[] conts = {new Next (), new Stop ()};

  private final int n;
  private final Continuation cont;

  Printable (int n) {
    this.n = n;
    this.cont = conts [n / 100];
  }

  public void print () {
    System.out.println (n);
    cont.call (n);
  }
}

interface Continuation {
  public void call (int n);
}

class Next implements Continuation {
  public void call (int n) {
    new Printable (n + 1).print ();
  }
}

class Stop implements Continuation {
  public void call (int n) {
    // intentionally empty
  }
}

class To100 {
  public static void main (String[] args) {
    new Printable (1).print ();
  }
}

EDIT: Since this question was closed (why???) I'll post my second answer here. It is inspired by Tom Hawtin's notice that the program doesn't have to terminate. Also the question doesn't require that only the numbers 1-100 are printed (or even in order).

To100Again.java:

class To100Again extends Thread {
  private static byte n;
  public void run () {
    System.out.println (n++);
    new To100Again ().start ();
    System.gc();
  }
  public static void main (String[] args) {
    new To100Again ().start ();
  }
}
trinithis
+7  A: 

Building on Yacoby's answer, but without the catch. (Upvote that answer.)

public class To100 {
    public static void main(String[] args) {
        final int max = 100;
        new java.util.concurrent.Semaphore(max) {
            void go() {
                acquireUninterruptibly();
                System.err.println(max-availablePermits());
                go();
            }
        }.go();
    }
}

Explanation:

  • Semaphore allows a specified number of permits to be acquired before blocking.
  • I didn't want to write java.util.concurrent twice, so I opportunistically extended Semaphore.
  • This uses an anonymous inner class. Anonymous does not mean it is not a type. I can therefore call a method on it that is not declared in a base type/implemented interface.
  • acquireUninterruptibly means I don't have to declare pesky checked exceptions.
  • Nobody said the program had to terminate.
Tom Hawtin - tackline
+1  A: 

And then God invented Perl (larry wall actually invented it.. :-)

#!/usr/bin/perl
@range = 1..100;
print @range;
in70x
Larry Wall is God? *Now* you tell me!
Chris Dwyer
Do you mean "God invented Perl ... Larry Wall actually implemented it"?
Andrew Grimm
Also no repetitive print statements,or a single print statement containing all the numbers from 1 to 100.
DeadMG
+20  A: 

In C++:

#include <iostream>

class a {
  static unsigned i;

public:
  a() {
    std::cout << ++i << std::endl;
  }
};

unsigned a::i = 0U;

int main() {
  a array[100];
}

This solution neither uses loops nor recursion for printing numbers from 1 to 100.

missingfaktor
+6  A: 

No conditions (no short-cut boolean operators, no ?-operator, no exceptions), no loops:

import java.util.Vector;

public class PrintOneToHundered {
  static int i;
  PrintOneToHundered() {}
  public String toString() { return ++i+""; }
  public static void main(String[] args) {
    Vector v1  =new Vector(); v1  .add(new PrintOneToHundered());
    Vector v2  =new Vector(); v2  .addAll(v1 ); v2  .addAll(v1 );
    Vector v4  =new Vector(); v4  .addAll(v2 ); v4  .addAll(v2 );
    Vector v8  =new Vector(); v8  .addAll(v4 ); v8  .addAll(v4 );
    Vector v16 =new Vector(); v16 .addAll(v8 ); v16 .addAll(v8 );
    Vector v32 =new Vector(); v32 .addAll(v16); v32 .addAll(v16);
    Vector v64 =new Vector(); v64 .addAll(v32); v64 .addAll(v32);
    Vector v100=new Vector(); v100.addAll(v64); v100.addAll(v32); v100.addAll(v4);
    System.out.println(v100);
  }
}

Explanation:

  • define a class, whose toString-method returns consecutive ints at repeated calls
  • create a vector with 100 elements, that are instances of the class
  • print the vector (toString-method of a Vector returns a string of the toString-values of all its elements)
Curd
+1  A: 

i would think there would be a java equivalent to something like the following php

$my_numbers = range(0,100);
echo implode($my_numbers, ' ');

this avoids recursion, loops, control statements, etc.

tim
There is no java equivalent for this.
Harsha
+2  A: 

Ok, I'm late on this and an answer is already accepted, but I wonder why nobody has used a clean and simple counter yet?

public class Counter
{
    static Counter[] vtab = new Counter[]
    {
        new Counter(),
        new Counter() { public void print( int first, int last ) {} }
    };

    public void print( int first, int last )
    {
        vtab[ ( last - first - 1 ) >>> 31 ].print( first, last - 1 );
        System.out.println( last );
    }

    public static void main( String[] args )
    {
        vtab[ 0 ].print( 1, 100 );
    }
}

Thread safe, configurable, no exceptions, no dependance on API side effects, just plain OOP and some trivial math.


For those not familiar with binary operators here is how it works:

  • The ( x >>> n ) expression moves all bits of the integer value x to the right by n places. Lower bits simply fall off the right side by this operation and new bits that come in from the left side are always 0.

  • So the effect of ( x >>> 31 ) is to move the highest bit of x to the lowest place and to set all other bits of x to 0. The result is now always either 0 or 1 for all possible values of x.

  • As the highest bit of an int is the sign bit which is 0 for positive values and 1 for negative values, the expression ( x >>> 31 ) evaluates to 0 for all positve values of x and to 1 for all negative values of x.

  • Now if both first and last are positive numbers and if last is greater than first, the result of ( last - first - 1 ) will be >= 0 and if last == first it will be -1.

  • So ( ( last - first - 1 ) >>> 31 ) evaluates to 0 if last is greater than first and becomes 1 if they are equal.

Now this value 0/1 is used to switch between the 2 implementations of print( int first, int last ) based on the comparision of first and last. At first the recursion takes place without printing anything. print( 1, 100 ) calls print( 1, 99 ) and so on... until last equals first which causes a switch to the other implementation of print which in turn does nothing at all. So now the stack unwinds again and the values are printed on the way down in ascending order and the invocation of vtab[ 0 ].print( 1, 100 ) finishes normally.

x4u
A: 

Didn't see this in here, using the termination order of the && operator.

public class count100 {

    public static boolean loop(int i) {
        System.out.println(100-i);
        return i > 0 && loop(i-1);
    }

    public static void main(String[] args) {
        loop(99);
    }
}
epatel
A: 

This answer is perverse enough that it doesn't even look like it will run. ;)

It gets extra text at the end of the output, but it avoid loops, conditions, main() and println(). ;)

public class OneHundred {
    private static int i = 1;
    static {
        OneHundred[] hundreds = new OneHundred[100];
        Arrays.fill(hundreds, new OneHundred(););
        Thread.currentThread().setName(Arrays.toString(hundreds).replaceAll("[\\]\\[, ]+", "\n"));
        clear("Exception in thread \""); clear("\" ");
    }
    private static void clear(String string) {
        try {
            Field f = String.class.getDeclaredField("count");
            f.setAccessible(true);
            f.set(string, 0);
        } catch (Exception ignored) { }
    }
    public String toString() { return "" + i++; }
}
Peter Lawrey
A: 

You don't need array's... just recursion... Try this...

public class TestFile {

/** * @param args */ public static void main(String[] args)throws Exception { TestFile f = new TestFile(); f.print(100); }

public void print(int x){ if(x>0){ System.out.println(x); x--; print(x); } } }

Harsha
OP said not to use `if` statements.
Loadmaster