Reputation: 15
I'm trying to get the following output from my code:
x o o o o
x x o o o
x x x o o
x x x x o
x x x x x
Here is my code:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
System.out.print(" x ");
} else {
System.out.print(" o ");
}
}
System.out.println();
}
But I'm not able to get the correct output. I'm getting the following output using this code:
x o o o o
o x o o o
o o x o o
o o o x o
o o o o x
Upvotes: 0
Views: 72
Reputation: 95
Just change if(i == j)
to if(j <= i)
and everything will work!
Long explanation:
Think about the logic
i
is the outer loop, take charge of each rowj
is the inner loop, print each character(x
and o
) with-in the linej
), depending on the line number (i.e. i
)j == 1
), to the i
position (j == i
), that is, j
from 1
to i
, which write in Java is j <= i
Upvotes: 2
Reputation: 9658
With the condition i == j
you will only get the x
in the diagonal elements. If you want the desired output then you'll have to modify the condition to i >= j
instead.
Here is the corrected code snippet:
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i >= j) {
System.out.print(" x ");
} else {
System.out.print(" o ");
}
}
System.out.println();
}
Output:
x o o o o
x x o o o
x x x o o
x x x x o
x x x x x
Upvotes: 0