1
public class F2E12 {

    public static final int DIM = 5;

    public static void main(String[] args) {
        printMatrix(DIM);

    }

    public static void printMatrix(int n) {
        int i = 0;
        int j = 0;
        for(;i<=n;i++) {
            for(;j<=n;j++) {
                System.out.print(j + " ");
            }
            System.out.print("\n");

        }
    }
}

I want to print a matrix which increments the first number of each row by one. The above code should produce:

  1. 0 1 2 3 4 5
  2. 1 0 1 2 3 4
  3. 2 1 0 1 2 3
  4. 3 2 1 0 3 4
  5. 4 3 2 1 0 1
  6. 5 4 3 2 1 0

Instead it prints. "0 1 2 3 4 5"

2 Answers 2

7
public static void printMatrix(int n) {
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            System.out.print(Math.abs(j - i) + " ");
        }
        System.out.print("\n");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

Your current code doesn't work because j hits n on the first iteration of i. You could move j into the loop like

// int j = 0;
for (; i <= n; i++) {
    int j = 0;
    for (; j <= n; j++) {

to fix that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.