Search code examples
javawhile-loopnested-loops

Nested loop pattern


If I have n numbers and the maximum number is 6 and the maximum letter is F, what is the best way to do it.

A1 
A2
A3
A4
A5 
A6 
B1
B2 
etc..

int numList = 36; 

         char letter;

        for (int i=1; i<=36; ++i){
            int a = numList/6;
            letter = 'A';
          for (int j=0; j<= a; j++){
            System.out.println(letter +"" + i);
            letter++;
          } 
    }

Solution

  • When you have a nested loop, the entire inner loop, along with the rest of the outer loop's body, is run every time the outer loop runs.

    Here, every time you run the inner for, the body of the inner loop is executed 6 times, which means you print 6 lines.

    So the way you've written it: the outer loop is executed 36 times, and each time the outer loop runs, the inner loop is executed 6 times. That means the inner loop is executed a total of 36*6 = 216 times, causing 216 lines to be printed. That isn't what you want. You want the outer loop to run only 6 times, so your first for needs to change.

    Another feature of nested loops: the inner loop repeats faster than the outer loop. So in your case, when the first iteration of the outer loop runs, the inner loop executes 6 times. Then we go to the next iteration of the outer loop, and the inner loop executes another 6 times; only then do we execute the outer loop the third time, and so on.

    According to your desired output, you want the digit to change faster than the letter. That means that the digit needs to be increased by 1 in the inner loop, and the letter needs to be increased in the outer loop. You're doing it backwards, though--you're increasing the letter in the inner loop, and the digit (i) in the outer loop.

    I don't want to give you the code--I hope I've given you enough information that you can fix it yourself. Please try doing this before you look at the code that others gave you.