You just need to see the pattern and replicate it in your code. Here is one way to solve this, which can also be used to produce larger matricies (set the max
variable to a different value):
public class main{
public static void main(String[] args){
int max = 5;
for(int i = 1; i < max; ++i){
for(int j = i; j < max; ++j)
System.out.print(" " + j);
for(int k = 1; k < i; ++k)
System.out.print(" " + k);
System.out.println();
}
}
}
Output when max = 5
:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
Output when max = 7
:
1 2 3 4 5 6
2 3 4 5 6 1
3 4 5 6 1 2
4 5 6 1 2 3
5 6 1 2 3 4
6 1 2 3 4 5
1
solved How do i print this using For nested loop?