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?
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?
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);
}
}
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);
}
}
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:)