The problem can be solved by making an association with an array. Imagine a generic array:
a11 a12 a13 a14
a21 a22 a23 a24
a31 a32 a33 a34
a41 a42 a43 a44
Where aij
, means row and column. Basically when doing coluna - linha
you get the solution to your problem. See (for convenience I've become negative):
-1+1 -1+2 -1+3 -1+4
-2+1 -2+2 -2+3 -2+4
-3+1 -3+2 -3+3 -3+4
-4+1 -4+2 -4+3 -4+4
Looking like this:
0 1 2 3
-1 0 1 2
-2 -1 0 1
-3 -2 -1 0
Then, in your code, check that coluna - linha
is greater than or equal to 0.
Returning to your code. It works partially because as the line variable increases, no white space equivalent to the indentation left by the negative numbers (from coluna - linha
operation) is added.
This can be fixed like this:
import java.util.*;
public class a{
public static void main(String[] args){
int coluna = 10;
while(coluna > 0){
System.out.println(" ");
int linha = 0;
//adicionar espacos (10 - coluna, comeca com 0 espaços e
//termina com 9 espacos em cada linha)
int espaco = 1;
while(espaco <= (10-coluna)){
//um espaco para o numero (ausente) e outro para
//separar os numeros
System.out.print(" ");
espaco++;
}
while(linha < coluna){
System.out.print(linha+" ");
linha++;
}
coluna--;
}
}
}
Or you can solve considering the array idea. Staying like this:
import java.util.*;
public class a{
public static void main(String[] args){
/**
a[linha][coluna]
matriz a = a11 a12 a13 a14 a15
a21 a22 a23 a24 a25
a31 a32 a33 a34 a35
coluna-linha=numero
*/
int linha= 0;
while(linha < 10){
System.out.println();
int coluna = 0;
while(coluna < 10){
if((coluna-linha) >= 0){
System.out.print((coluna-linha) + " ");
}else{
System.out.print(" ");
}
coluna++;
}
linha++;
}
}
}
Using for loop:
import java.util.*;
public class b{
public static void main(String[] args){
/**
a[linha][coluna]
matriz a = a11 a12 a13 a14 a15
a21 a22 a23 a24 a25
a31 a32 a33 a34 a35
coluna-linha=numero
*/
for(int linha = 0; linha < 10; linha++){
for(int coluna = 0; coluna < 10; coluna++){
if((coluna-linha) >= 0){
System.out.print((coluna-linha) + " ");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
In both cases, the expected result comes out:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6
0 1 2 3 4 5
0 1 2 3 4
0 1 2 3
0 1 2
0 1
0
Different from what happened before:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8