Loops in Java
Subject: Data Structures and Algorithms · Language: Java · Level: beginner · 6 min read
Learn for loop, while loop, do while loop, enhanced for loop, break, and continue.
A loop is used to repeat a block of code multiple times. Instead of writing the same statement again and again, we write it once inside a loop and control how many times it should run. Loops are one of the most important parts of programming because many problems require repeated work. Printing numbers from 1 to `n`, reading array elements, calculating a sum, searching for a value, and printing patterns all need loops.
In Java, the main loops are `for`, `while`, and `do while`. Java also provides an enhanced `for` loop, which is useful for reading values from arrays and collections.
for Loop
A `for` loop is usually used when we know how many times the loop should run. It keeps initialization, condition, and update in one line, so it is very common in counting and array problems.
```java
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
```
In this loop, `int i = 1` is the initialization, `i <= 5` is the condition, and `i++` is the update. Java first creates `i`, then checks the condition, then runs the body, and finally updates `i`. A `for` loop is commonly used when traversing arrays because indexes usually move from `0` to `n - 1`.
```java
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
```
while Loop
A `while` loop is useful when repetition depends on a condition and we may not know the exact number of repetitions in advance. The condition is checked before the loop body runs.
```java
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
```
Here, the loop continues as long as `i <= 5` is true. If the condition is false at the beginning, the body will not run even once. A `while` loop is useful in problems where we repeat until something changes, such as reading digits of a number, moving pointers, or searching until a condition is found.
do while Loop
A `do while` loop runs the body first and checks the condition later. This means the loop body runs at least once, even if the condition is false.
```java
int choice;
do {
System.out.println("Menu shown once");
choice = 0;
} while (choice != 0);
```
`do while` is useful in menu-driven programs where the menu should appear at least one time before checking whether the user wants to continue.
Enhanced for Loop
The enhanced `for` loop is used to read values from arrays or collections easily. It is also called the for-each loop because it visits each value one by one.
```java
for (int value : arr) {
System.out.println(value);
}
```
Use the enhanced `for` loop when you only need the values. Use the normal `for` loop when you need indexes, when you want to update array values, or when you need to compare the current element with nearby elements.
break and continue
`break` stops the loop immediately. It is useful when the answer is found and there is no need to continue checking the remaining values.
```java
if (arr[i] == target) {
found = true;
break;
}
```
`continue` skips the current iteration and moves to the next round of the loop. It is useful when some values should be ignored.
```java
if (arr[i] < 0) {
continue;
}
```
Here, negative values are skipped, and the loop continues with the next element.
Infinite Loop
An infinite loop happens when the loop condition never becomes false. This usually happens when the update is missing or written incorrectly. For example, if `i++` is missing from a `while` loop, the value of `i` may never change, and the loop may keep running. Always make sure the loop moves toward stopping.
Example Program
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); System.out.print("Enter n: ");
int n = sc.nextInt();
int sum = 0; for (int i = 1; i <= n; i++) {
sum += i;
} System.out.println("Sum = " + sum); System.out.print("Numbers: ");
int i = 1;
while (i <= n) {
System.out.print(i + " ");
i++;
}
System.out.println();
}
}
```
This program uses a `for` loop to calculate the sum from `1` to `n` because the number of repetitions is clear. It uses a `while` loop to print numbers from `1` to `n`, showing that the same repeated work can also be controlled with a condition.
Loops in DSA
Loops are used in almost every DSA topic. Arrays need loops for traversal, strings need loops for character checking, searching uses loops to find a target, and sorting algorithms use nested loops or repeated passes. When solving a problem, first identify what work is repeated. Then decide whether you need indexes, values, or condition-based repetition. This will help you choose the correct loop.
Practice Question
Take a number as input and print its multiplication table from 1 to 10. Then modify the program to calculate the sum of all table values.