Loops in Java

A loop is a basic programming technique that helps a block of code to be executed repeatedly. It allows you to iterate over a sequence of instructions multiple times, making it easier to perform repetitive tasks or process a collection of data.

Loops are used to automate repetitive operations, such as iterating over an array or a list, or executing a set of statements until a specific condition is met. By using loops, you can avoid writing duplicate code and make your programs more efficient and concise.

There are typically three types of loops in Java:

  1. for loop
  2. while loop
  3. do while loop


for Loop

The for loop is used to iterate over an array or list of items for a specified number of times. A for loop is commonly used when you know the number of iterations in advance. It consists of three components:

  1. Initialization: This part is used to initialize a loop variable before the loop starts. It typically involves assigning an initial value to a counter variable. The initialization is executed only once, at the beginning of the loop.

  2. Termination (Condition): This is the condition that is checked before each iteration of the loop to determine whether the loop should continue or terminate. The loop only terminates when the condition becomes false. After the loop ends, the execution of the program moves on to the next statement after the loop.

  3. Increment (or Decrement): The increment statement is responsible for updating the loop variable after each iteration. It specifies how the loop variable should change for each iteration. The increment statement is executed at the end of each iteration, just before the condition is checked again.

Here's the general syntax of a for loop:

for (initialization; termination; increment) {
    // code to be executed repeatedly
}


Example:

To demonstrate how for loop works, lets print the numbers from 1 to 10 using a for loop in Java:

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

In this example, the int i = 1 initializes the loop variable i to 1. The termination condition i <= 10 checks if i is less than or equal to 10. If it is true, the loop body is executed, and i is incremented by 1 (i++) at the end of each iteration. The loop continues until the termination condition evaluates to false.

The output of the above code is as follows:

1
2
3
4
5
6
7
8
9
10

By adjusting the initialization, termination, and increment parts of the for loop, you can control the number of iterations and customize the behavior to suit your specific needs.

enhanced for loop

The for loop also has another form of for loop referred to as the enhanced loop to work with arrays and collection. It is also known as for-each loop. It was introduced in Java version 5.0. It can be used to make loops more compact and easy to read.

Here's the general syntax for a for-each loop:

for (elementType element : arrayOrCollection) {
    // Code to be executed each element
}

In this syntax, elementType represents the type of elements in the array or collection, element is a variable that represents each individual element in the iteration,  arrayOrCollection is the array or collection over which you want to iterate.

Here's an example to iterate over an array using the for-each loop:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

for (int number : numbers) {
   System.out.println(number);
}

In this example, the for-each loop iterates over each element in the numbers array and assigns the value of each element to the number variable. The loop body, which is the System.out.println(number) statement, is executed for each element, resulting in the numbers 1 to 10 being printed.


The for-each loop can also be used with collections such as lists or sets. Here's an example with a List:

List<String> fruits = Arrays.asList("Mango", "Orange", "Banana", "Apple");

for (String fruit : fruits) {
   System.out.println(fruit);
}

In this example, the for-each loop iterates over each element in the fruits list and assigns the value of each element to the fruit variable. The loop body, which is the System.out.println(fruit) statement, is executed for each element, resulting in the names of the fruits being printed.

The for-each loop simplifies the process of iterating over elements in an array or collection, making the code more concise and readable.


while loop

The while loop is used when the number of iterations is not known in advance but the loop should continually execute a block of statements until a specific condition is true. Its syntax can be expressed as:

while (expression) {
    // statements to be executed
}

In a while loop, the condition is checked before each iteration. If the condition results to true, the code inside the loop is executed. After each iteration, the condition is checked again, and if it remains true, the loop continues. If the condition becomes false, the loop ends, and the program moves on to the next statement after the loop.

To demonstrate the working of a while loop, let see an example where we want to print the numbers from 1 to 10 using a while loop:

int i = 1;

while (i <= 10) {
   System.out.println(i);
   i++;
}
In this example, the loop starts with i initialized to 1. The condition i <= 10 is checked before each iteration. As long as i is less than or equal to 10, the code inside the loop is executed. After each iteration, i is incremented by 1 (i++) to move towards the termination condition. The loop continues until i becomes 11, at which point the condition i <= 10 becomes false, and the loop terminates.

Example:

public class Example {

   public static void main(String[] args) {
      int i = 1;
      while (i <= 10) {
	 System.out.println(i);
	 i++;
      }
   }

}

The output of the above code is as follows:

1
2
3
4
5
6
7
8
9
10


do-while loop

A do-while loop is used when the requirement is to execute the loop body at least once even if the condition results to false. In a while loop, the condition is checked before executing the loop body but in do-while loop, the condition is always checked after the loop body is executed which guarantees that the loop body to be executed at least once, regardless of the initial condition.

Here's the general syntax of do-while loop:

do {
     // Code to be executed
} while (condition);

In do-while loop, the condition is checked after executing the loop body at least once.

Here's an example to print the numbers from 1 to 10 using a do-while loop:

int i = 1;

do {
    System.out.println(i);
    i++;
} while (i <= 10);

In this example, the loop starts with i initialized to 1. The code inside the loop is executed first, which prints the value of i. Then, i is incremented by 1 (i++). After each iteration, the condition i <= 10 is checked. As long as the condition is true, the loop continues. Once i becomes 11, the condition becomes false, and the loop terminates.

Example:

public class Example {

   public static void main(String[] args) {
      int i = 1;
      do {
	  System.out.println(i);
	  i++;
      } while (i <= 10);
   }

}

Output:

1
2
3
4
5
6
7
8
9
10