Summary - Loops
- Java course
- Beginner
- Lesson 47/116
- 5 min
Combine for, while and for-each to write a multiplication table.
Summary - Loops
In this group you learned loop structures:
- for: counting loop
- while: conditional loop
- do-while: at least once
- break/continue: loop control
- for-each: walks an array without an index
These structures let you write repeated work in short code. Now combine them and write a multiplication table.
Practice Multiplication table (2)
Write a Main class with a main method. Write for (int i = 1; i <= 5; i++). Each turn print System.out.println(2 * i). This makes the first 5 rows of the 2 times table.
Sample solution
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(2 * i);
}
}
}Expected output
2 4 6 8 10
Practice Array sum (for-each)
Write a Main class with a main method. Assign {2, 4, 6} to int[] nums. Assign 0 to int sum. With for (int n : nums) do sum += n. Finally print System.out.println(sum).
Sample solution
public class Main {
public static void main(String[] args) {
int[] nums = {2, 4, 6};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum);
}
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which loop runs the body at least once?
- for-each
- for
- while
- do-while Correct answer
Explanation: do-while runs the body first, then tests the condition.
2 Match the loop structures
| Term | Meaning |
|---|---|
for |
Counting |
while |
Condition |
do-while |
At least 1 |
for-each |
No index |
3 Complete the for-each
int[] nums = {1, 2, 3};
for (int n : ____) {
System.out.println(n);
}
int[] nums = {1, 2, 3};
for (int n : nums) {
System.out.println(n);
}
Explanation: for-each walks the nums array.