-1
public class Main {

    public static void main(String[] args) {
        int numTiles = 8;
        for(int i=0; i<numTiles;i++){
            for(int j=0; j<numTiles;j++){
                if(i==0 || i==numTiles-1){
                    System.out.print("1");  
                }else if (i+j==numTiles-1){
                    System.out.print("1");              
                }else{
                    System.out.print(" ");
                }               
            }
            System.out.println();
        }
    }
}

I see that it starts off with a for loop that repeats depending on the value of numTiles. Then the second for loop repeats 8 times and prints out 8 1s. I do not understand the else-if and the else in the for-loop.

If I could get clarification on the else-if and else conditionals it would be appreciated.

GalAbra
  • 5,048
  • 4
  • 23
  • 42

2 Answers2

1

i is the row number and j is the column number. (This is true because the println only happens when i increments, not j.)

When i==0, you're on the top row, and when i==numTiles-1, you're on the bottom row. Thus, the first if statement prints the top and bottom horizontal lines of the Z.

When i+j==numTiles-1, you're on the main diagonal. Thus, the second if statement prints the diagonal line of the Z.

Since a Z is just a top and bottom horizontal line and a diagonal line, together, those print all of it.

1

i represents the row index, while j represents the columns.

  • The if prints the top and bottom rows.
  • The else if prints the diagonal, as it's equivalent to the linear function x + y = c (only where x,y are i,j).

Consider the following equivalent code in Javascript, where I switched the print inside the else if to the digit 2:

let numTiles = 8;
for (let i = 0; i < numTiles; i++) {
  let row = "";
  for (let j = 0; j < numTiles; j++) {
    if (i == 0 || i == numTiles - 1) {
      row += "1";
    } else if (i + j == numTiles - 1) {
      row += "2";
    } else {
      row += " ";
    }
  }
  console.log(row + '\n');
}
GalAbra
  • 5,048
  • 4
  • 23
  • 42