Using Nested Loops
Nested Loops
Just like when we need to nest an if statement within another if statement, we can nest a loop within another loop. When nested loops are executes, for every iteration of the outer loop, the inner loop will iterate to completion. The nested loops do not need to be of the same type.
We have explored three types of loops:
Nested while loops
In this animation we see how to trace while loops that are nested together.
Your Turn
Try this in the Java Playground.
Nested for Loops
We can re-write the while loop above using for loops instead.
- Outer loop: what is the initialization expression, boolean expression, and step expression for this loop?
- What are the three things happening in this outer loop?
- Inner loop: what is the initialization expression, boolean expression, and step expression for this loop?
- What are the two things happening in the inner loop?
- Complete the re-write below. Run the code and see if you get the same output.
Computing Student Averages
This program prompts the user to enter the number of grades for each student. We are using two different loop structures for this program. It will compute and print the average for each student. The program will then prompt to see if there is another student to compute the average. It's important to initialize gradeTotal to 0 before any grades are entered. This variable needs an initial value in order to be a part of a sum.
Try it in your IDE!
int gradeTotal;
String input = IO.readln("How many grades?");
int numGrades = Integer.parseInt(input);
do {
gradeTotal = 0;
for (int gradeCount = 1; gradeCount <= numGrades; gradeCount++) {
input = IO.readln("Enter a grade.");
grade = Integer.parseInt(input);
totalGrades += grade;
}
IO.println("Average: " + (totalGrades/numGrades));
input = IO.readln("Do you have more students? Enter yes or no");
} while (input.equals("yes"));
Next Learn Tutorial