-2

My question is simple, I would like to print all the possible 4 digit combinations of 0-9:

Like:

0001
0002
0003
.
.
.
0009
0010
0011
.
.
.
9991
9992
9993
9994
9995
9996
9997
9998
9999

How can I do?

Biffen
  • 6,249
  • 6
  • 28
  • 36
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • What are the constraints? – shmosel Mar 08 '15 at 11:22
  • I feel this question should be more specific. There are two parts to the solution: a loop of some kind, and a way to add the appropriate amount of zeros (which doesn't even get mentioned). If there are no limitations or constraints, then the user is just asking how to make a loop, in which case the question is probably is a duplicate – 1owk3y Mar 08 '15 at 11:33

3 Answers3

2

You just need one loop from 0 to 1000. To add leading zeros you can use String.format or System.out.format.

You can find example here.

It's little bit shorter and prettier than accepted answer from Apurva (my opinion :) ).

Example code (\n adds new line):

public static void printNumbers(int num) {
    for (int i = 0; i <= num; i++) {
        System.out.format("%03d\n", i);
    }
}
Community
  • 1
  • 1
Pyro2266
  • 310
  • 2
  • 5
  • 18
1

Put one for loop and iterate from 0 to 9999

Set conditions inside for loop also, if value is less than 10 then add three 0, if value is less than 100 then add two 0, if value is less than 1000 then add one 0

As you want all 4 digit combinations of 0 to 9, 0000 will also be accounted.

for(int i=0; i<=9999; i++){
    if(i<10){
        System.out.println("000"+i);
    }
    else if(i<100){
        System.out.println("00"+i);
    }
    else if(i<1000){
        System.out.println("0"+i);
    }
    else{
        System.out.println(i);
    }
} 
Apurva
  • 7,871
  • 7
  • 40
  • 59
  • 3
    Please avoid "Code Only" answers, especially for questions that are clearly homework/learning tasks - what will the OP learn form this answer? (Other than the usage of copy+paste)? – amit Mar 08 '15 at 11:17
  • @amit I posted only code at first because, I read on meta stackoverflow that be the first to answer, and then make edits in that – Apurva Mar 08 '15 at 11:21
0

You can simply create an integer that runs from 0 (or 1) to 9999, and print it with heading zeros, it will generate all possible combinations, and is quite easy to implement.

Implementation is left to you, you do have to learn from this assignment:)

amit
  • 175,853
  • 27
  • 231
  • 333
  • Will the downvoter please comment? I tried to explain the OP how to approach the problem without spoon-feeding him the answer. – amit Mar 08 '15 at 11:22