Reputation: 41
A question has asked me to create a loop that will count in 3s up to 300. I am able to get that part but it then asks when it reaches 30, I must create a new line and then add 30 again so it will be come 60 and then a new line will be created again.
This is my code so far:
int x;
int z = 30;
for (x = 3; x <= 300; x = x + 3 ) {
System.out.print(" " + x);
if (x == z) {
System.out.println("");
z = z + 30;
}
}
Here is the output:
3 6 9 12 15 18 21 24 27 30
33 36 39 42 45 48 51 54 57 60
63 66 69 72 75 78 81 84 87 90
93 96 99 102 105 108 111 114 117 120
123 126 129 132 135 138 141 144 147 150
153 156 159 162 165 168 171 174 177 180
183 186 189 192 195 198 201 204 207 210
213 216 219 222 225 228 231 234 237 240
243 246 249 252 255 258 261 264 267 270
273 276 279 282 285 288 291 294 297 300
Upvotes: 0
Views: 85
Reputation: 48693
You should honestly, be using indexes and multiplying them by the step to determine when to start and end your loop.
This is easier to understand, and easier to follow.
public class NumberPrinter {
public static void main(String[] args) {
printNumbers(1, 100, 3, 10);
}
static void printNumbers(int startIndex, int endIndex, int step, int linelimit) {
int start = step * startIndex;
int end = step * endIndex;
int mod = step * linelimit;
while (start <= end) {
System.out.printf(" %3d", start);
if ((start % mod) == 0) {
System.out.println();
}
start += step;
}
}
}
Upvotes: 1