I have a problem that involves matrices, what I need to do is fill a matrix of N * M of dimension (that is, of a number n of columns and rows given by the user), with even numbers. example:
I have come up with the code, but I can not make the series increase diagonally, also when the matrix is square (4 * 4 example) the program runs normally), but otherwise, if it is n * m (What is requested, I have the display and an error.) Besides, the series must start from the top right (which already achieved), and end at the bottom right (but with the succession of pairs diagonally) How can I make the series of even numbers is generated diagonally exactly as in the previous example? My code:
int val;
int lonv;
int fil;
int col;
int su=2;
int matriz[][];
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Ingrese el nro de filas para la matriz: ");
fil=Integer.parseInt(br.readLine());
System.out.println("Ingrese el nro de columnas para la matriz: ");
col=Integer.parseInt(br.readLine());
matriz=new int [fil][col];
for(int i=0; i<fil; i++)
{
for(int j=(col-1); j>=0; j-- )
{
if(matriz[i][j]<= 2)
{
matriz[i][j]= su;
su+=2;
}
else
{
System.out.println("");
matriz[i][j]= su;
su+=2;
}
}
}
for(int i=0; i<col; i++)
{
for(int j=0; j<col; j++)
{
System.out.print(matriz[i][j]+" ");
}
System.out.println("");
}
I leave the code run for each case:
* Run of the program with square matrix (erroneous)
Run of the program with matrix of n m (erroneous)