+ 2

Matrix

Hello everyone. I have been trying to solve this Matrix program wherein if user enters 4, it will generate 16 numbers; if 3, it will generate 9 numbers. I am struggling on the else-if statements. The output must be arranged just like this: 16 15 14 13 9 10 11 12 8 7 6 5 1 2 3 4 This is my current program: import java.util.Scanner; public class Matrix { public static void main(String[] args) { Scanner mtrx = new Scanner(System.in); int matrixNum = 4; int row, col; int ai = 0, deductor = 0, adder = 1; System.out.print("Enter matrix to generate (n by n): "); matrixNum = mtrx.nextInt(); for(row = 1; row <= matrixNum; row++) { for(col = 1; col <= matrixNum; col++) { if(col == 1) { ai = matrixNum*matrixNum - deductor; }else if((col % 2) == 0) { ai = matrixNum*col - deductor; }else { ai += adder; } System.out.print(ai + "\t"); } System.out.println(); deductor = deductor + matrixNum; adder +=2; } } }

8th Dec 2021, 3:08 AM
Angel Lyn
Angel Lyn - avatar
4 Respostas
+ 3
If something is not clear, ask. int n = mtrx.nextInt(); int ai = n * n; for(int row=1; row <= n; row++){ for(int col=1; col <= n; col++){ if(row > 1 && col == 1) ai-=n; if(row%2 == 0) System.out.print(++ai +" "); else System.out.print(ai-- +" "); } System.out.println(); }
8th Dec 2021, 8:23 AM
Solo
Solo - avatar
+ 3
After getting the value for n, create a new matrix n x n. int[][] matrix = new int[n][n]; Then you can loop through the matrix filling it in with an incrementing value, starting from the last row (n-1) and the first column (0). Loop to the end of that row filling in your incrementing value, then step up a row to (n-2) at the last column (n-1) and work towards the first column (0) filling in the values. Then again step up and work forward to the end of the next row etc. Repeat until all the rows are full (row == -1). Here's some example code; https://code.sololearn.com/cqppy4AuVVg5/?ref=app
8th Dec 2021, 4:41 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
This one doesn't use an array, it just prints the values ... https://code.sololearn.com/cS0SznbHlWcb/?ref=app
8th Dec 2021, 6:00 AM
Ipang
+ 3
Thank you all so much for helping.
8th Dec 2021, 1:02 PM
Angel Lyn
Angel Lyn - avatar