The Z-Pattern Maze


Hi everyone,

I am taking a course in Java but I’m having a hard time with the following code (sorry if it dumb).
When we print we get the 1’ in a Z shape.

What I don’t understand, is why we get a lot of 1’ in the first and last row?
If my understanding is correct, code should check first condition (i < Numtiles) and then move on to the next line and so on.

Can you please help me understand?

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){
				}else if (i+j==numTiles-1){
					System.out.print(" ");


Sounds like you should read the code and execute it manually, observing what you end up doing. Because it says right there in the code what it does, nothing stopping you from finding out all by yourself.
You’re also free to change the code in various ways to see what effect that has.
Printing out the decisions made is also an option, either to stderr or a file or commenting out the current output and only looking at what your new prints say (what you may want to find out is the order that things happen in)
Or write your own program that does the same thing, just for the sake of working through the problem. It’s often difficult to understand something until you’ve written it yourself and through that forced yourself to consider all that is involved.

Yeah it may take some time, but do you need to know what this code does or do you need to be able to tell what code does? Maybe spending time is exactly what should be happening here. At least now you have a few suggestions for how to approach this.


It took me some time but I finally understood how it works.
Feels good to find the solution.

Thanks for the tips.



This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.