The problem can be solved by making an association with a matrix. Imagine a Generic matrix:
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
the solution to your problem is obtained. See (for convenience I have 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
Thus remaining:
0 1 2 3
-1 0 1 2
-2 -1 0 1
-3 -2 -1 0
So just, in your code, check if coluna - linha
is greater than or equal to 0.
Back to your code. It works partially, because as the variable line increases there are added blank spaces equivalent to the recoil left by the negative numbers (of operation coluna - linha
).
It 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 idea of matrix. Getting 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 loop for:
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 cited comes out the expected result:
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 than 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
Try to write a table test of your code.
– Woss
How was the output of your code? Was an inverted triangle, check?
– Jefferson Quesado