Topic 1 - Variables and Data Types
Topic 2 - Conditionals and Strings
Topic 3 - Loops
Topic 4 - Arrays
Topic 5 - File Handling
Semester 1 Projects
Topic 6 - Classes/Objects and Methods
Topic 7 - ArrayLists
Semester Projects

Nested For Loops

We’ll now look at what happens when you combine two loops together. Things can get pretty wild. We’ve created a DrawingBuddy class that contains one method, “drawSquare()”. This method is then called in main and we see that square is drawn on the console.

drawSquare() has two loops:

The inner loop will run 5 times for every iteration in the outer loop. The outer loop runs for 3 iterations. After every outer loop iteration, we tell the computer to stop printing on this line and instead print on the next line with, System.out.println().

The inner loop prints five asterisks in a row on the same line. Notice that it uses .print instead of .println().

Practice Problem – Printing a triangle

Change the code so that it draws a triangle in DrawingBuddy. This should draw a triangle of any size by using nested for loops.