mercredi 8 août 2018

Learning C++ confused by "maze" pattern

Ok everyone i'm taking a free course on EDX and I can't get some of the activities earlier In lesson to work so I had to dive head first into this.

The program creates a "zig zag" pattern, the size of which depending on the int numTiles. I am confused by this because running through the program in my head I think it would way work waaay differently. I don't know why it prints 1 for the entire line depending on the numTiles. Wouldn't the program stop at the point? Why don't J and I increase everytime? What case would be the spaces? Do I or J ever go over the int numtiles? How does J ever equal 0 except in the first time it runs? Please help me wrap my head around this.

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

}

Aucun commentaire:

Enregistrer un commentaire