VisualStudioTutor.com Java Tutorial All Lessons

Lesson 10 of 20

Loops

Repeat program actions with for, while, and do-while loops.

Learning objectives

  • Choose an appropriate loop for a task.
  • Control repetition with counters and conditions.
  • Use break and continue carefully.
  • Recognize and avoid infinite loops.
  • Build a repeated-input mini project.

1. for loops

A for loop is ideal when the number of repetitions is known or controlled by a counter.

Example: print 1 to 5

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

2. while loops

A while loop checks its condition before each repetition. It may execute zero times.

int balance = 100;

while (balance >= 20) {
    balance -= 20;
    System.out.println("Remaining balance: " + balance);
}

3. do-while loops

A do-while loop checks the condition after the body, so the body runs at least once.

int choice = 1;

do {
    System.out.println("Menu displayed");
    choice++;
} while (choice <= 3);

4. break and continue

for (int i = 1; i <= 10; i++) {
    if (i == 3) {
        continue; // skip 3
    }

    if (i == 8) {
        break;    // stop the loop
    }

    System.out.println(i);
}

Mini project: marks average

import java.util.Scanner;

public class MarksAverage {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("How many marks? ");
        int count = Integer.parseInt(input.nextLine());

        int total = 0;

        for (int i = 1; i <= count; i++) {
            System.out.print("Enter mark " + i + ": ");
            int mark = Integer.parseInt(input.nextLine());
            total += mark;
        }

        double average = (double) total / count;
        System.out.printf("Average: %.2f%n", average);

        input.close();
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
Infinite loopThe loop condition never becomes false.Make sure a control variable changes inside the loop.
Off-by-one errorThe boundary uses < instead of <=, or vice versa.Test the first and last expected iterations.
Division by zero when count is 0The program allows zero items.Validate that count > 0 before calculating an average.

Summary

Loops remove repetitive code and are essential for processing groups of data. Lesson 11 combines loops with arrays so you can store and process multiple related values.