Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Nested loop with 4 rows and 6 columns printing 1 5 9 13 17 21 2 6 10 14 18 22 3 7 11 15 19 23 4 8 12 16 20 24

public class practice { public static void main (String[] args){ int row =4; int column = 6;

printGrid(row,column);
}   
private static void printGrid(int row, int column) {
    for( int i = 1; i <= row;i++){
        System.out.print(i);
    for(int j = 1; j <= column; j++){
        System.out.print(?);
        }
        System.out.println( );
    }
}

} I need help finding the right equation

2 Answers

Here is what I did:

public class forLoop {
  public static void main(String[] args) {

  int row = 4;
   int column = 6;
   int number = 0;

  for (int i = 1; i <= row; i++){
 for (int j = 1; j <= column; j++) {
 number = i + (j*row) - row;
   if(number >= 10) {
   System.out.print(number + "  "); 
   }
   else {
     System.out.print(number + "   ");
   }

 }
 System.out.println("");
 }
}

}

This is my solution:

public static void main(String[] args) { int maxRow = 4; int maxColumn = 6; int number = 0;

    for (int row = 1; row <= maxRow; row++){
        for (int column = 1; column <= maxColumn; column++) {
            number = row + 4*(column-1);
            System.out.printf("%d   ", number);
        }

        System.out.println("");
    }
}

the output is:

1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24

Each successive column is 4 more than the last. Since it's a nested for loop, you would increase the column for each row. The first number needs to be 1, so I subtract one from the column count. Hope that helps.