-5

I want to display 1 to 100 without using loops. I already tried storing 1-100 in array but it also requires use of loops.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Pallav
  • 165
  • 1
  • 2
  • 14

6 Answers6

1

Try this (Java 8)

IntStream.range(1, 100).forEach(n -> { System.out.println(n); });

However, implementation of range() as well as forEach() uses loops, so, the solution may be on the edge of cheating.

If you consider the code above as cheating, you can emulate loop, via, say, recursion:

private static void printIt(int n) {
  System.out.println(n);

  if (n < 100)
    printIt(n + 1);
}

...

printIt(1);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 6
    You are using a loop. OP ask for a solution with out using loops. – Jens Feb 11 '15 at 07:24
  • 4
    But that `forEach`... I mean... Technically speaking... It is still a loop ;D – Matt Clark Feb 11 '15 at 07:24
  • Eh... Technically, `forEach` is not a *loop* by itself, its a *method* which, however, uses a loop... Actually, `range()` should use loop as well. So the solution is on the edge of cheating – Dmitry Bychenko Feb 11 '15 at 07:54
0

Use toString() method like this:

System.out.println(array.toString());

It converts array to this:

[1,2,3,4...]

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])

Zlopez
  • 660
  • 1
  • 5
  • 11
0

Try this,

import java.util.Arrays;

Code

int[] array = new int[] { 1, 2, 3, ... , 100 };
System.out.println(Arrays.toString(array));

Output:

[1, 2, 3, 4, ... , 100]

Java.util.Arrays.toString(int[ ]) Method

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
0

You never said it had to print them only once or that program had to terminate successfully:

public static void main(String args[])
{
    print(0);
}

private static void print(int i)
{
    System.out.println((i % 100) + 1);
    print(i+1);
}
Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
0
public static void main(String[] args) {
    print(100);
}

private static void print(int n) {
    if(n > 1) {
        print(n-1);
    }
    System.out.println(n);
}
hack4m
  • 285
  • 2
  • 5
  • 11
-1

Try Below code

 public static void main(String[] args) {
    int[] i = {1,10,50};
    System.out.println(Arrays.toString(i));
  }
Keval
  • 1,857
  • 16
  • 26