Reputation: 167
I am trying to print a loop of numbers, with 10 numbers per line. Here is what I have done so far:
for(int i = 100; i < 200; i++) {
System.out.print(i++);
System.out.print(" ");
}
The output I get is
100 101 102 103 104 105 106 107 108 109 110 111....
I have tried creating another loop with variable j < 11 and then putting System.out.println() however that just prints 10 returns then the next number. I am trying to accomplish this output:
100 101 102 103 104 105 106 107 108 109
110 111 112 113...
Upvotes: 2
Views: 31476
Reputation: 3820
I can't understand how can you get that output because you are incrementing i in for loop and inner body of loop also
for(int i = 100; i < 200; i++) {
System.out.print(i+" ");
if(i%10==0)
System.out.print("\n");
}
Upvotes: 2
Reputation: 93
for (int i = 100; i < 200; i++) {
if (i != 100 && i % 10 == 0) {
System.out.println("");
}
System.out.print(i + " ");
}
Upvotes: 2
Reputation: 28538
try ternary operator ?:
If your input is fixed from 100 to 200 then you can try:
for(int i = 100; i < 200; i++) {
System.out.print(i+ ((i%10==9) ? "\n" : " "));
}
will output:
100 101 102 103 104 105 106 107 108 109
110 111 112 113 114 115 116 117 118 119
120 121 122 123 124 125 126 127 128 129
130 131 132 133 134 135 136 137 138 139
...
But if you input is not fixed then try ie 105 to 200:
int start = 105;
for(int i = start; i < 200; i++) {
System.out.print(i+ ((i-(start-1))%10==0 ? "\n" : " "));
}
will output:
105 106 107 108 109 110 111 112 113 114
115 116 117 118 119 120 121 122 123 124
125 126 127 128 129 130 131 132 133 134
...
Upvotes: 7
Reputation: 1445
Try this
for(int i = 100; i < 200; i++) {
System.out.print(i+ " ");
if(i%10 == 9)
System.out.println();
}
Upvotes: 1
Reputation: 734
for(int i = 100; i < 200; i++) {
if(i%10==0){
System.out.println();
}
System.out.print(i+" ");
}
Upvotes: 2
Reputation: 503
for(int i = 100; i < 200; i++) {
if (i>100 && i % 10 == 0) {
System.out.println();
}
System.out.print(i);
System.out.print(" ");
}
Upvotes: -2
Reputation: 29
try this
int counter=1;
for(int i = 100; i < 200; i++) {
if(counter==10)
{
counter=1;
System.out.println("\n");
}
else
{
System.out.print(i++ + " ");
counter++;
}
System.out.println("");
}
Upvotes: -1