Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No. Pattern print

Tags:

java

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 
like image 415
Ajay Kumar Avatar asked Dec 11 '22 02:12

Ajay Kumar


1 Answers

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.

like image 134
peter.petrov Avatar answered Dec 22 '22 07:12

peter.petrov