Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to arrange this 2D array diagonally with zeros around

This is the code i came up so far, the goal is to generate a table 10×10 just like in the image what i need
The problem i can’t seem to understand is why it doesn’t generate zeros and the last number 27 and just throws everything together.

public class Main {

    public static void main(String[] args) {
        int values[][] = new int [10][10];
       
      int n = 1;
        for (int i=0; i<=9; i++) {
            for (int j=9-i; j>=7-i; j--){
                 if (j >=0){
                values[i][j] = n++;
}
                 System.out.printf(values[i][j] + " ");
            }
           System.out.println();
        }
    }
}

I would appreciate any suggestions, thanks!

What is see/get — > what i see/ error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code works. You just have to fill your arrays with 0s before running your algorithm.

Take a look:

// don't forget to import java.util
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int values[][] = new int [10][10];
        // here you fill the array with zeros
        for (int[] row : values) {
            for (int col : row) {
                row[col] = 0;
            }
        }
        
        // here is your algorithm
        int n = 1;
        for (int i=0; i<=9; i++) {
            for (int j=9-i; j>=7-i; j--){
                if (j >=0){
                    values[i][j] = n++;
                }
            }
        }
        
        // here you print out the array
        for (int[] row : values) {
            System.out.println(Arrays.toString(row));
        }
    }
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading