33

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.

Thunderhashy
  • 5,291
  • 13
  • 43
  • 47

45 Answers45

177

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.
Community
  • 1
  • 1
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • 5
    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 Jan 11 '10 at 19:21
  • 1
    Can someone explain how does the above code work? – Thunderhashy Jan 11 '10 at 22:04
  • 1
    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 Jan 12 '10 at 00:21
  • 19
    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 Jan 12 '10 at 00:23
  • 1
    @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 Jan 12 '10 at 03:05
  • 1
    @Tom, but well, you can find a lot of libs that have loops internally, imo it's not a valid answer. – bestsss Jun 12 '11 at 19:25
119

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.

z -
  • 7,130
  • 3
  • 40
  • 68
  • 4
    Wow, congrats on figuring out exactly how much heap space this takes. – Robert Fraser Jan 11 '10 at 23:54
  • 2
    @silky: I see no loop, it is a recursive call. That is an awesome way IMO – Guvante Jan 12 '10 at 00:54
  • 1
    Guvante: I shouldn't need to point out how obvious it is that a recursive call is a loop. – Noon Silk Jan 12 '10 at 01:32
  • 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 Jan 12 '10 at 03:55
  • 11
    @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. – Mark Bolusmjak Jan 12 '10 at 05:23
  • 2
    @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 Jan 12 '10 at 15:36
  • 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. – user192472 Mar 03 '10 at 14:40
  • could have done it w/o heap crash but stackoverdflow which is controllable by new Thread – bestsss Jun 12 '11 at 19:26
70

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\"?");
Niki
  • 15,662
  • 5
  • 48
  • 74
64

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

How to print 1 to 100 without any looping using C#

Here is the Java version:

public class Application {

    public static void main(String[] args) {
        Print64Numbers();
        Print32Numbers();
        Print4Numbers();
    }

    private static int currentNumber = 0;

    private static void Print1Number() { System.out.println(++currentNumber); }
    private static void Print2Numbers() { Print1Number(); Print1Number(); }
    private static void Print4Numbers() { Print2Numbers(); Print2Numbers(); }
    private static void Print8Numbers() { Print4Numbers(); Print4Numbers(); }
    private static void Print16Numbers() { Print8Numbers(); Print8Numbers(); }
    private static void Print32Numbers() { Print16Numbers(); Print16Numbers(); }
    private static void Print64Numbers() { Print32Numbers(); Print32Numbers(); }
}
Community
  • 1
  • 1
Adam Pope
  • 3,234
  • 23
  • 32
  • 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) – Ponkadoodle Jan 11 '10 at 23:01
48

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
  • 54,544
  • 15
  • 116
  • 120
41

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);
mthurlin
  • 26,247
  • 4
  • 39
  • 46
  • Of course I am looking for a different solution rather than repetitive printing. – Thunderhashy Jan 11 '10 at 18:46
  • 128
    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 Jan 11 '10 at 18:48
  • 1
    No offense to truppo but isn't this also the most obvious answer EVER? – matt b Jan 11 '10 at 18:50
  • 1
    @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 Jan 11 '10 at 18:54
  • 3
    This doesn't work. Ok, it prints the numbers from 1 to 5, but what with the three dots? – Daniel Daranas Jan 11 '10 at 19:01
  • 68
    @Gregory I think this gets most votes because it's a straightforward, but basically useless answer to a stupid, useless question. – Michael Borgwardt Jan 11 '10 at 19:10
  • 26
    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 Jan 11 '10 at 19:12
  • 1
    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 Jan 11 '10 at 19:16
  • 1
    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 Jan 11 '10 at 19:24
  • @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 Jan 11 '10 at 19:30
  • Optimized version: http://stackoverflow.com/questions/2044033/print-numbers-from-1-to-100-in-java-without-using-any-loops-or-conditions/2044291#2044291 – OscarRyz Jan 11 '10 at 19:31
  • @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 Jan 11 '10 at 19:37
  • 1
    @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 Jan 11 '10 at 21:17
  • 2
    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 Jan 11 '10 at 23:58
  • 13
    This is the only correct answer; every other one is using a loop of some variety (either directly or indirectly). – Noon Silk Jan 12 '10 at 00:12
  • 1
    I'll defend this answer, it's basically a lookup table and those are perfectly acceptable in many applications. – temp2290 Jan 13 '10 at 16:48
  • 2
    I think a loop was used to create this code lines... – user85421 Feb 04 '10 at 17:18
36

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
  • 90,905
  • 62
  • 285
  • 365
22

download from pastebin

System.out.println((new URL("http://pastebin.com/pastebin.php?dl=f722c7eb0")).getContent())
Jimmy
  • 89,068
  • 17
  • 119
  • 137
16

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?

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
15

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
  • 31
  • 4
12

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
  • 129,300
  • 32
  • 216
  • 265
  • "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 – Ponkadoodle Jan 11 '10 at 22:55
  • This code is not complete. How do you create the list with 100 items? – Jorn Jan 11 '10 at 23:09
  • I thought that would be self explanatory, but I'll add that for completeness. – LBushkin Jan 11 '10 at 23:50
12

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
  • 145,806
  • 30
  • 211
  • 305
10

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));
}
user85421
  • 28,957
  • 10
  • 64
  • 87
  • 1
    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 Jan 11 '10 at 20:34
9

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
  • 12,169
  • 3
  • 35
  • 49
7

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
  • 2,280
  • 5
  • 33
  • 43
6

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
  • 13,877
  • 6
  • 48
  • 58
5

Here's a hint that be helpful.

The assert statement isn't the forbidden if statement.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
5

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 ();
  }
}
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
4

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
  • 48,893
  • 5
  • 92
  • 171
4

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

Kallin Nagelberg
  • 989
  • 8
  • 17
3

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

b_erb
  • 20,932
  • 8
  • 55
  • 64
3

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);
}
Sajad Bahmani
  • 17,325
  • 27
  • 86
  • 108
3

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 Deutsch
  • 14,629
  • 5
  • 53
  • 72
3

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
  • 51
  • 1
3

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
  • 49,173
  • 15
  • 109
  • 139
  • 1
    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 Jan 11 '10 at 23:36
  • I see a conditional in timer.Enabled = (i < 101); – Loren Pechtel Nov 09 '10 at 04:35
  • @Loren: That's a boolean assignment. – Austin Salonen Nov 09 '10 at 04:51
  • @Austin: It's a boolean assignment of a conditional. – Loren Pechtel Nov 10 '10 at 02:01
  • @Loren: Neither `timer.Enabled` nor `(i < 101)` are conditionals... Like I said in my comment, the underlying classes do the checks but this code merely sets the values the Timer class acts upon. http://en.wikipedia.org/wiki/Conditional_(programming) – Austin Salonen Nov 10 '10 at 05:56
  • @Austin: How can you say i < 101 is not a conditional? – Loren Pechtel Nov 11 '10 at 03:29
  • @Loren: Conditionals "are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false." As an example, "if p, then q" is a conditional; "p" by itself is not a conditional. – Austin Salonen Nov 11 '10 at 04:18
  • @Austin: And turning a timer on or off based on a boolean comparison isn't a conditional?? – Loren Pechtel Nov 14 '10 at 04:26
  • @Loren: Did you read my first comment?? – Austin Salonen Nov 15 '10 at 15:08
  • @Austin: But the conditional isn't hidden. It's being used to calculate the true/false status. Expand that i < 101 and you'll find a conditional jump in opcodes. – Loren Pechtel Nov 16 '10 at 04:12
  • @Loren: This wasn't written in opcode; it was written in C#. If you're choosing level on which no conditionals can exist, the only solution is dedicated hardware because the JVM or CLR has checks when the app is loaded; the OS has checks when the JVM or CLR are loaded; the OS has checks when the JVM or CLR get processor time; ...; the hardware has checks when it's powered up. – Austin Salonen Nov 16 '10 at 05:17
  • @Austin: I figured "no conditionals" meant in the program logic as otherwise it's obviously impossible. I would say anything that compiles the provided code (but not the library itself, I'm sure the number-printing routine contains loops and conditionals) into a conditional jump should be considered a conditional. Pete Kirkham's solution uses no such conditionals. – Loren Pechtel Nov 16 '10 at 22:29
3

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
  • 45,805
  • 17
  • 110
  • 144
2

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.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
2

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
  • 525,659
  • 79
  • 751
  • 1,130
2
public class PrintUptoHundredWithoutIf {
    public static void main(String[] args) {
        Thread t = new Thread(task());
        t.setDaemon(true);
        t.start();
        sleep((NUMBERS_TO_PRINT * SLEEP_PERIOD_IN_MILLIS)
                + OS_SLEEP_RESPONSE_IN_MILLIS);
    }

    private static final int SLEEP_PERIOD_IN_MILLIS = 1000;
    private static final int NUMBERS_TO_PRINT = 100;
    private static final int OS_SLEEP_RESPONSE_IN_MILLIS = 110;

    public void printUptoHundred(byte seq) {
        int posVal = Math.abs(~seq);
        System.out.println(posVal);
        sleep(SLEEP_PERIOD_IN_MILLIS);
        printUptoHundred((byte) posVal);
    }

    private static Runnable task() {
        return new Runnable() {
            @Override
            public void run() {
                new PrintUptoHundredWithoutIf().printUptoHundred((byte) 0);
            }
        };
    }

    private static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
1

//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();
    }
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Zaje
  • 2,281
  • 5
  • 27
  • 39
1

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
  • 12,169
  • 3
  • 35
  • 49
1

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
  • 78,473
  • 57
  • 200
  • 338
  • 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. – Thunderhashy Jan 12 '10 at 00:33
  • 3
    Isn't ruby a higher level language than Java? – Andrew Grimm Jan 12 '10 at 00:35
  • 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. – Thunderhashy Jan 12 '10 at 00:45
  • @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 Jan 12 '10 at 01:39
  • Ruby/Python are not higher level than Haskell. Here's a Haskell solution for kicks: `mapM print [1..100]`. – Thomas Eding Jan 12 '10 at 02:46
  • 2
    Making the Java vs Ruby argument is comparing apples to oranges. – gpampara Jan 12 '10 at 05:37
  • Ruby is as strongly typed as Java. The difference is that Java is statically typed; Ruby dynamically typed. – Wayne Conrad Jan 19 '10 at 01:04
  • "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. – Dan Rosenstark May 15 '10 at 17:53
  • @Yar: "The IDE writes 99% of the code for you in Java." - was that meant to be humor or serious? – Andrew Grimm Aug 19 '11 at 07:30
  • @Andrew Grimm, it was serious, but I meant that most of the boilerplate code is written by the IDE. Although in the last year I've rethought this -- conciseness is nice -- I would still take longer code vs. no IDE help any day. And yes, I use RubyMine, so I get as much help as possible with Ruby, but frankly there's not much a compiler can do with dynamic (yet strong) typing. – Dan Rosenstark Aug 19 '11 at 12:30
  • @Andrew Grimm, the problem with this answer, though, is that Ruby's looping for you anyway. But then again, the question is kind of stupid in the first place, so it's all good. – Dan Rosenstark Aug 19 '11 at 12:34
  • I don't know Ruby,but how is that (1..100) not a loop statement? It is in other languages. – orbfish Nov 05 '11 at 02:55
1
public class Main {
        // prints 2 numbers starting from i  
        private static void print2(int i) { 
            System.out.println(i);
            System.out.println(i+1);
        }
       // prints 10 numbers starting from i
        private static void print10(int i) { 
            print2(i);
            print2(i+2);
            print2(i+4);
            print2(i+6);
            print2(i+8);
        }
       // prints 20 numbers starting from i
        private static void print20(int i) {
            print10(i);
            print10(i+10);
        }
        // prints 100 numbers starting from i
        private static void print100(int i) {
            print20(i);
            print20(i+20);
            print20(i+40);
            print20(i+60);
            print20(i+80);
        }

        public static void main(String[] args)  {
                 print100(1);
        } 

}

Or (among other many alternatives) :

public class Main {
        private static void print1(int i) {
            System.out.println(i);
        }
        private static void print4(int i) {
            print1(i);
            print1(i+1);
            print1(i+2);
            print1(i+3);
        }
        private static void print16(int i) {
            print4(i);
            print4(i+4);
            print4(i+8);
            print4(i+12);
        }
        private static void print64(int i) {
            print16(i);
            print16(i+16);
            print16(i+32);
            print16(i+48);
        }

        public static void main(String[] args) throws Exception {
                 print64(1);
                 print16(1+64);
                 print16(1+64+16);
                 print4(1+64+32);
        } 

}
leonbloy
  • 73,180
  • 20
  • 142
  • 190
0
List<Integer> list = new AbstractList<Integer>() {
    public int size() { return 100; }
    public Integer get(int i) { return i + 1; }
};
System.out.println( list.toString() );
ignis
  • 8,692
  • 2
  • 23
  • 20
0

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

#!/usr/bin/perl
@range = 1..100;
print @range;
in70x
  • 1,170
  • 1
  • 10
  • 16
0

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
  • 1
  • 1
0

As I said there: How to print 1 to 100 without any looping using C#

public static void f(int[] array, int n)
{
    System.out.println(array[n] = n);
    f(array, n + 1);
}
public static void main(String[] args) {
    try { f(new int[101], 1); }
    catch (Exception e) { }
}
Community
  • 1
  • 1
Shay Ben Moshe
  • 1,298
  • 3
  • 12
  • 27
0

Here's a solution that seems very simple compared to what has been posted so far. It uses short-circuit evaluation to end recursion:

public class Foo {
  static int x = 1;
  public static void main(String[] args) {
    foo();
  }

  private static boolean foo() {
    System.out.println(x++);
    return x > 100 || foo();
  }
}
Joe K
  • 18,204
  • 2
  • 36
  • 58
  • Possible duplicate (same idea): http://stackoverflow.com/questions/2044033/display-numbers-from-1-to-100-without-loops-or-conditions/2045859#2045859 – user85421 Jul 22 '11 at 21:05
-1
public class Run3 
{
    public static void number(int i)
    {
    if(i==100)
    {
    return; 
    }
    else
    {
        i++;
        System.out.println(i);
        number(i);
    }
    }
public static void main(String[] args)
{
number(0);

}
}
-1
public class Test {

static int x = 0;
public static void main(String[] args) {

    printTo100();

}
public static void printTo100(){
    if(x<=100)
    {
    System.out.println(x+"");
    x++;
    printTo100();
    }

}

}
kleopatra
  • 51,061
  • 28
  • 99
  • 211
-1
 system("seq 1 100");

in C will give the desired result. Find the equivalent Java call to run a shell command.

ldog
  • 11,707
  • 10
  • 54
  • 70
-1

Does Clojure count because it runs on the JVM?

(range 1 101)

or:

(take 100 (iterate inc 1))

Both work directly at the REPL (which includes an implied print).

mikera
  • 105,238
  • 25
  • 256
  • 415
-2
public class nub
 {

 static int i=1;

 public static void main(String...a)
  {

    if(i<=1000)//suppose my range is 10000
    {
        System.out.println(i);
        i++;
        main();
    }

  }

}    
ignis
  • 8,692
  • 2
  • 23
  • 20
-3

You don't need array's. You can do that with 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);
        }
    }
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
skis
  • 71
  • 1
  • 6
-6

Try :

int i = 1;
System.out.println(i++);
System.out.println(i++);
System.out.println(i++);
....
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
  • 3
    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 Jan 11 '10 at 19:16
  • 1
    -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. – Thomas Eding Jan 12 '10 at 02:48