How to print this pattern
1 2 3
4 5 6
7 8 9
I tried to do this way
for (int i = 1; i <= 3; i++) {
for (int j = i; j <= i + 2; j++) {
System.out.print(j);
System.out.print(" ");
}
System.out.println();
}
But, it gave me this output
1 2 3
2 3 4
3 4 5
Try this. This is OK.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(3*(i-1) + j);
System.out.print(" ");
}
System.out.println();
}
Why does it work?
Well ... if you watch carefully, you see that
on row i
, you have these 3 numbers:
3*(i-1)+1
, 3*(i-1)+2
, 3*(i-1)+3
(the last number is the one divisible by 3).
So that's your general formula.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With