Ticker

6/recent/ticker-posts

Java While Loop

Java While Loop:

Introduction: 

The Java while loop is used to repeatedly execute a block of code as long as a specified condition evaluates to true. It is commonly used when the number of iterations is not known beforehand.

Syntax:

java
while (condition) {
// Code to be executed repeatedly as long as the condition is true
}

Example:

java
public class WhileLoopExample {
public static void main(String[] args) {
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
}
}

Explanation:
In this example, we use a while loop to print the value of the variable count from 1 to 5. The loop will continue executing as long as the condition count <= 5 is true. The count is incremented by 1 in each iteration to avoid an infinite loop.

Java Do-While Loop:

Introduction:
The Java do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once before checking the loop condition. The condition is evaluated after the execution of the loop body.

Syntax:

java
do {
// Code to be executed at least once
} while (condition);

Example:

java
import java.util.Scanner;

public class DoWhileLoopExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Enter a positive number (0 to exit): ");
number = scanner.nextInt();
System.out.println("You entered: " + number);
} while (number != 0);
scanner.close();
}
}

Explanation:
In this example, we use a do-while loop to continuously prompt the user to enter a positive number. The loop will execute at least once, as the condition is checked after reading the user input. If the user enters 0, the loop will exit.

Enhanced While and Do-While Loop to Iterate Java Array:

Introduction:
In Java, we can use the enhanced while or do-while loop to iterate through elements of an array without using an index variable explicitly. This approach simplifies the code and makes it more readable.

Example:

java
public class ArrayIterationExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

// Enhanced While Loop
int index = 0;
while (index < numbers.length) {
System.out.println("Element at index " + index + ": " + numbers[index]);
index++;
}

// Enhanced Do-While Loop
int index2 = 0;
do {
System.out.println("Element at index " + index2 + ": " + numbers[index2]);
index2++;
} while (index2 < numbers.length);
}
}

Explanation:
In this example, we have an array numbers containing integer elements. We demonstrate both the enhanced while and do-while loops to iterate through the array elements. The enhanced loops eliminate the need for an explicit index variable and directly access the elements using the array's length. Both loops will print the elements and their corresponding indices. The loops will continue until all the elements in the array are visited.

Post a Comment

0 Comments