3.4 Lab - Loops in Java

Introduction

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.

Objectives

By the end of this lab, you will be able to:

  1. Understand and use for, while, and do-while loops.
  2. Write Java programs that use loops to perform repetitive tasks.
  3. Implement loops to interact with user input and process data.
  4. Compile and run Java programs using different types of loops.

Lab Steps

Step 1: Access the Linux Terminal
  1. Open the terminal on your Linux system.
  2. Ensure you are in your home directory by running the command:
    cd ~
    
Step 2: Create and Edit a Java File
  1. Create a new Java file using Nano called LoopsExample.java:
    nano LoopsExample.java
    
  2. Type the following Java code into the file to use a 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);
        }
    }
    
  3. Save the file by pressing CTRL + O, then hit Enter to confirm the filename.
  4. Exit Nano by pressing CTRL + X.
Step 3: Compile the Java Program
  1. In the terminal, compile the Java program using the javac command:
    javac LoopsExample.java
    
  2. If there are no errors, this command will create a file named LoopsExample.class. Verify this by running:
    ls
    
Step 4: Run the Java Program
  1. Run the compiled program using the java command:
    java LoopsExample
    
  2. The program will display output for each of the loops as follows:
    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
    
Step 5: Modify the Program
  1. Open the LoopsExample.java file again using Nano:
    nano LoopsExample.java
    
  2. Modify the program to include a loop that sums the numbers from 1 to 10 using a 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);
    
  3. Save, exit, recompile, and run the program to see the new result:
    javac LoopsExample.java
    java LoopsExample
    
Step 6: Add User Input
  1. Modify the program to ask the user for a number and then use a 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);
            }
        }
    }
    
  2. Save, exit, recompile, and run the program. The program will now ask for a number, and the loop will print all numbers from 1 to the entered value:
    javac LoopsExample.java
    java LoopsExample
    
Step 7: Experiment with Infinite Loops (Optional)
  1. Modify the program to create an infinite loop using a while loop:
    // Infinite loop
    int x = 1;
    while (true) {
        System.out.println("Infinite loop iteration: " + x);
        x++;
    }
    
  2. Save, exit, and compile the program. When you run it, the loop will run indefinitely, so you will need to stop it by pressing CTRL + C in the terminal.
Step 8: Cleanup (Optional)
  1. Once you're done, clean up the directory by removing the .class files:
    rm *.class
    

Summary

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.