JustYou are doing a simple ternary using the two loops :lot of if-condition to find what you need to print. This works but this is a verbose. You could find some logic in what you want to print.
for(int x = 0; x < 10 ; ++x){
for(int y = 0; y < 10 ; ++y){
System.out.print(x < y ? 'o' : 'x');
}
System.out.println();
}
ThisYour output is a simple square matrix that you want to split by it's diagonal. Here is the matrix :
- The diagonal is when
x = y
. - if
x < y
: we are on the right -> O - if not
x < y
: we are on the left or on the diagonal -> X
And withhere is what you want to print (with the same spaces)
x o o o o o o o o o
x x o o o o o o o o
x x x o o o o o o o
x x x x o o o o o o
x x x x x o o o o o
x x x x x x o o o o
x x x x x x x o o o
x x x x x x x x o o
x x x x x x x x x o
x x x x x x x x x x
You can see some pattern here. Every place you want an o
is on the right of the diagonal.
So you can write this as a condition depending on x
and y
like this :
- if
x < y
: we are on the right of the diagonal-> O - if not
x < y
: we are on the left or on the diagonal -> X
You could use a if-else to print x
or o
but I like to do it on one line so I used use a simple ternary condition: (ternary is simple condition ? true statement : false statement
)
for(int x = 0; x < 10 ; ++x){
for(int y = 0; y < 10 ; ++y){
System.out.print(x < y ? 'o' : 'x');
}
System.out.println();
}