In this lab, you will learn how to use loops in Java to repeat a block of code multiple times. Loops are essential in programming because they allow you to automate repetitive tasks and process collections of data efficiently. You will explore the three main types of loops in Java: the for
loop, the while
loop, and the do-while
loop.
By the end of this lab, you will be able to:
for
, while
, and do-while
loops.cd ~
LoopsExample.java
:nano LoopsExample.java
for
loop to print numbers from 1 to 5:public class LoopsExample {
public static void main(String[] args) {
// For loop example
System.out.println("For Loop: Numbers 1 to 5");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// While loop example
System.out.println("\nWhile Loop: Numbers 6 to 10");
int j = 6;
while (j <= 10) {
System.out.println(j);
j++;
}
// Do-While loop example
System.out.println("\nDo-While Loop: Numbers 11 to 15");
int k = 11;
do {
System.out.println(k);
k++;
} while (k <= 15);
}
}
CTRL + O
, then hit Enter
to confirm the filename.CTRL + X
.javac
command:javac LoopsExample.java
LoopsExample.class
. Verify this by running:ls
java
command:java LoopsExample
For Loop: Numbers 1 to 5
1
2
3
4
5
While Loop: Numbers 6 to 10
6
7
8
9
10
Do-While Loop: Numbers 11 to 15
11
12
13
14
15
LoopsExample.java
file again using Nano:nano LoopsExample.java
for
loop:// For loop to calculate the sum of numbers 1 to 10
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("\nSum of numbers 1 to 10: " + sum);
javac LoopsExample.java
java LoopsExample
for
loop to print all numbers from 1 up to the user’s number:import java.util.Scanner;
public class LoopsExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask for user input
System.out.print("Enter a number: ");
int userNumber = scanner.nextInt();
// For loop to print numbers from 1 to the user's number
System.out.println("\nNumbers 1 to " + userNumber + ":");
for (int i = 1; i <= userNumber; i++) {
System.out.println(i);
}
}
}
javac LoopsExample.java
java LoopsExample
while
loop:// Infinite loop
int x = 1;
while (true) {
System.out.println("Infinite loop iteration: " + x);
x++;
}
CTRL + C
in the terminal..class
files:rm *.class
In this lab, you learned how to use for
, while
, and do-while
loops to repeat code execution in Java. You explored how each loop works, used loops to sum numbers, interact with user input, and even create an infinite loop. Mastering loops will enable you to automate repetitive tasks and handle larger data sets effectively in your Java programs.