TashevTD
TashevTD

Reputation: 13

Filling a vertical matrix Java

I'm trying to fill a matrix vertically, but 1 row is missing. Can you help me ? There is the code. Maybe there is an easier way to fill a matrix verically, but i cant find it.

public static void main(String[]args){
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the value of matrix: ");
    int n = input.nextInt();

    int [][] matrix = new int [n][n];


    for (int i = 1; i < matrix.length; i++) {
        matrix[0][i] = matrix[0][i -1] + n;

    }

    for(int i = 1; i < matrix.length; i++){
        for (int j = 0; j < matrix.length; j++){
        matrix[i][j] = matrix[i -1][j] + 1;

        System.out.print(matrix[i][j] + " ");

        }
            System.out.println();

    }

            input.close();
}

Output: Enter the value of matrix: 4 1 5 9 13 2 6 10 14 3 7 11 15

Upvotes: 1

Views: 1380

Answers (4)

user4624062
user4624062

Reputation:

Try

 public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();

int [][] matrix = new int [n][n];

matrix[0][0]=0;  //you have forgotten the first value
for (int i = 1; i < matrix.length; i++) {
    matrix[0][i] = matrix[0][i -1] + n;
    //initializing the first line
}

for(int i = 1; i < matrix.length; i++){
    for (int j = 0; j < matrix.length; j++){
    matrix[i][j] = matrix[i -1][j] + 1;
    }

    // re-loop to display but this time start with i=0
   for(int i = 0; i < matrix.length; i++){
    for (int j = 0; j < matrix.length; j++){
     System.out.print(matrix[i][j] + " ");
    }

        System.out.println();

}

        input.close();
}

Upvotes: 0

The Javatar
The Javatar

Reputation: 719

There is an easier way of doing this:

keep a variable like count and iterate the matrix on columns first then rows:

int count = 1; // or 0 if you start with 0
int[][] a = new int[n][n];
for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++) {
         a[j][i] = count; // notice j first then i 
         count++;
    }

After that you can easly print out the values:

for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
        System.out.println(a[i][j]);

Upvotes: 0

DiSol
DiSol

Reputation: 414

Your row is missing because you never printed it in your first loop (the one that is initializing your first line) - you should have a row of 0 4 10 12 at the beginning. But you could do it much easier with only one nested loop.

Upvotes: 1

Aditya Singh
Aditya Singh

Reputation: 2453

To fill a matrix vertically, you must loop through columns in the outer loop and through rows in the inner(nested) loop. For example:

for(int j = 0; j < matrix.length; j++) {

    for(int i = 0; i < matrix.length; i++) {

        matrix[i][j] = /* The value you want to fill */;
        .../* Other stuff you wanna do */
    }
}

Upvotes: 0

Related Questions