Free Ebook cover Java for Beginners: A Complete Introduction to Programming with Java

Java for Beginners: A Complete Introduction to Programming with Java

New course

10 pages

Loops in Java: Repeating Tasks with for, while, and do-while

Capítulo 6

Estimated reading time: 7 minutes

+ Exercise

Why Loops Matter

A loop repeats a block of code while a condition is true (or for a known number of times). Loops help you avoid writing the same statements again and again, and they make programs easier to change and maintain.

In Java, the most common loops are while, for, and do-while. You will also use break and continue to control loop flow.

1) The while Loop: Condition-Based Repetition

Use a while loop when you want to repeat something as long as a condition stays true, and you may not know in advance how many repetitions will happen.

Syntax

while (condition) {    // code to repeat}

How it works: Java checks the condition first. If it is true, the body runs. After the body finishes, Java checks the condition again, and so on.

Example: Counting Up (Step-by-Step)

Goal: print numbers 1 through 5.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

int i = 1;while (i <= 5) {    System.out.println(i);    i++;}
  • Start: i = 1
  • Check: i <= 5 is true, print 1, then increment to 2
  • Repeat until i becomes 6, then the condition is false and the loop stops

Trace Table (Debugging Tool)

A trace table helps you “see” how a loop changes variables each iteration.

Iteration | i (before) | condition i<=5 | printed | i (after)----------------------------------------------------------1         | 1          | true           | 1       | 22         | 2          | true           | 2       | 33         | 3          | true           | 3       | 44         | 4          | true           | 4       | 55         | 5          | true           | 5       | 66         | 6          | false          | -       | -

Example: Summing Numbers with while (Step-by-Step)

Goal: sum numbers from 1 to 5. Expected result: 15.

int i = 1;int sum = 0;while (i <= 5) {    sum += i;    i++;}System.out.println(sum);
  • Initialize: sum starts at 0
  • Each iteration adds the current i to sum
  • Increment i so the loop progresses toward stopping
Iteration | i (before) | sum (before) | sum += i | sum (after) | i (after)-----------------------------------------------------------------------1         | 1          | 0            | +1       | 1           | 22         | 2          | 1            | +2       | 3           | 33         | 3          | 3            | +3       | 6           | 44         | 4          | 6            | +4       | 10          | 55         | 5          | 10           | +5       | 15          | 6

Example: Validating Input Until Correct

A classic use of while is “keep asking until the input is valid.” For example, keep prompting until the user enters a positive number.

int n = -1;while (n <= 0) {    System.out.print("Enter a positive number: ");    n = scanner.nextInt();}System.out.println("You entered: " + n);
  • If the user enters 0 or a negative number, the condition stays true and the loop repeats.
  • When the user finally enters a positive number, the condition becomes false and the loop ends.

2) The for Loop: Counted Repetition

Use a for loop when you know (or can express) how many times you want to repeat. It groups initialization, condition, and update in one place.

Syntax

for (initialization; condition; update) {    // code to repeat}
  • initialization: runs once at the start
  • condition: checked before each iteration
  • update: runs after each iteration

Example: Counting with for (Step-by-Step)

Goal: print numbers 1 through 5.

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

Read it as: “Start i at 1; while i is at most 5, print it; after printing, increase i by 1.”

Example: Summing Numbers with for

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

Example: Printing a Simple Pattern (Nested for Loops)

Patterns are a practical way to understand nested loops (a loop inside another loop). The outer loop controls rows; the inner loop controls columns.

Goal: print a 4x6 rectangle of *.

int rows = 4;int cols = 6;for (int r = 1; r <= rows; r++) {    for (int c = 1; c <= cols; c++) {        System.out.print("*");    }    System.out.println();}
  • Outer loop runs 4 times (rows).
  • For each row, inner loop prints 6 stars (columns).
  • println() moves to the next line after each row.

Goal: print a right triangle of height 5.

int height = 5;for (int r = 1; r <= height; r++) {    for (int c = 1; c <= r; c++) {        System.out.print("*");    }    System.out.println();}
  • Row 1 prints 1 star, row 2 prints 2 stars, etc.
  • The inner loop limit uses r, so the number of stars grows each row.

3) The do-while Loop: At-Least-Once Execution

Use do-while when the loop body must run at least once. The condition is checked after the body runs.

Syntax

do {    // code to repeat} while (condition);

Notice the semicolon at the end: while (condition);

Example: Input Validation That Must Prompt Once

If you want to prompt the user at least once, do-while is often the cleanest choice.

int n;do {    System.out.print("Enter a number from 1 to 10: ");    n = scanner.nextInt();} while (n < 1 || n > 10);System.out.println("Accepted: " + n);
  • The prompt runs once no matter what.
  • If the number is outside the range, the condition is true and the prompt repeats.

Loop Control: break and continue

break: Exit the Loop Immediately

break stops the nearest loop right away, even if the condition is still true.

Example: search for the first multiple of 7 between 1 and 50.

int found = -1;for (int i = 1; i <= 50; i++) {    if (i % 7 == 0) {        found = i;        break;    }}System.out.println(found);
  • As soon as a multiple of 7 is found, the loop ends.
  • This avoids unnecessary iterations.

continue: Skip to the Next Iteration

continue skips the rest of the current iteration and jumps to the next loop cycle.

Example: sum only odd numbers from 1 to 10.

int sum = 0;for (int i = 1; i <= 10; i++) {    if (i % 2 == 0) {        continue;    }    sum += i;}System.out.println(sum);
  • When i is even, the loop skips sum += i.
  • Only odd values contribute to the sum.

Common Mistakes and Debugging Tips

1) Infinite Loops

An infinite loop happens when the condition never becomes false.

Common causes:

  • Forgetting to update the loop variable (missing i++ or similar).
  • Updating the variable in the wrong direction (e.g., i-- when you need i++).
  • Using a condition that can never become false.

Example of a bug (missing increment):

int i = 1;while (i <= 5) {    System.out.println(i);    // i++ is missing, so i stays 1 forever}

Debugging tips:

  • Add a temporary print to show variable values: System.out.println("i=" + i);
  • Use a trace table to confirm that variables change each iteration.
  • If you suspect an infinite loop during testing, add a safety counter temporarily.

2) Off-by-One Errors

Off-by-one errors happen when a loop runs one time too many or one time too few. They often come from mixing up < and <=, or starting at the wrong initial value.

Example: printing 1 to 5, but using < incorrectly:

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

This prints 1 to 4, not 1 to 5.

Debugging tip: write down the intended first and last values, then check:

  • Initialization matches the first value.
  • Condition allows the last value.
  • Update moves toward stopping.

3) Changing the Wrong Variable in Nested Loops

In nested loops, make sure the inner loop updates its own counter, and the outer loop updates its own counter.

Bug example (inner loop increments the wrong variable):

for (int r = 1; r <= 3; r++) {    for (int c = 1; c <= 3; r++) {        System.out.print("*");    }    System.out.println();}

This can cause an infinite loop or incorrect output because c never changes and r changes too fast.

Debugging tip: temporarily print both counters inside the inner loop:

System.out.println("r=" + r + ", c=" + c);

4) Misplaced Semicolon

A stray semicolon can create an empty loop body.

Bug example:

for (int i = 1; i <= 5; i++); {    System.out.println("Runs once, not 5 times");}

The semicolon ends the loop immediately, so the block runs once after the loop finishes.

Debugging tip: if a loop seems to do nothing, check for an accidental semicolon right after ).

Choosing the Right Loop

  • Use while when repetition depends on a condition and the number of iterations is not fixed (input validation, reading until a sentinel value).
  • Use for when you can describe the repetition with a counter (counting, indexing, fixed ranges, many patterns).
  • Use do-while when the body must run at least once (menus, prompts that must appear before checking validity).

Now answer the exercise about the content:

Which situation is the best match for using a do-while loop instead of a while loop?

You are right! Congratulations, now go to the next page

You missed! Try again.

A do-while checks its condition after running the body, so the code inside executes at least once (useful for prompts/menus that must appear before validation).

Next chapter

Methods in Java: Creating Reusable Code Blocks

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.