Loops
In programming, loops are used to repeatedly execute a block of code as long as a certain condition is met. They are essential to many tasks in programming, from running calculations on multiple data values to game logic.
In Java, there are three main types of loops:
For loop
: Executes a block of code a specific number of times.While loop
: Executes a block of code as long as a certain condition is true.Do-While loop
: Executes a block of code at least once, and then repeats as long as a certain condition is true.
Here's how each one can be used in Java:
For loop
for (int i = 0; i < 5; i++) {
System.out.println("The value of i is: " + i);
}
This for loop prints the value of i
five times. It starts by setting i
to 0. Then, before each iteration, it checks if i
is less than 5. If it is, it executes the code block and then increments i
by 1. Once i
is no longer less than 5, it stops.
While loop
int j = 0;
while (j < 5) {
System.out.println("The value of j is: " + j);
j++;
}
This while loop does the same thing as the previous for loop. It starts by setting j
to 0. Then, as long as j
is less than 5, it prints the value of j
and increments j
by 1.
Do-While loop
int k = 0;
do {
System.out.println("The value of k is: " + k);
k++;
} while (k < 5);
This do-while loop also does the same thing as the other loops. However, it ensures the block of code is executed at least once before checking the condition.
Nested Loops and Loop Control Statements
You can also put a loop inside another loop to form a nested loop. In Java, a break
statement can be used to exit a loop prematurely, and a continue
statement can be used to skip to the next iteration of the loop.
Tasks
- Write a for loop that prints the numbers 1 to 10.
- Write a while loop that prints the numbers 1 to 10.
- Write a do-while loop that prints the numbers 1 to 10.
-
Write a nested for loop that prints a 5x5 matrix of asterisks (*). Example:
***** ***** ***** ***** *****
-
Write a for loop that prints the numbers 1 to 10, but uses a
break
statement to exit the loop when the loop variable is 6. - Write a for loop that prints the numbers 1 to 10, but uses a
continue
statement to skip printing the number 5.
Additional Resources
Oracle Java Documentation - The for Statement
Oracle Java Documentation - The while and do-while Statements