How to Use For, While, and Do While Loops in Java With Examples
Loops are an essential part of programming as they allow us to automate repetitive tasks. Among the different types of loops available in Java, the most commonly used ones are the for, while, and do while loops. In this article, we will explore how to use these loops in Java with examples.
The for loop in Java
The for loop is used when we want to execute a block of code repeatedly for a fixed number of times. The syntax of the for loop is as follows:
“`
for(initialization; condition; increment){
//code to be executed
}
“`
Here, initialization sets the variable value before the loop starts, the condition checks the condition before every loop iteration, and the increment increases the variable value after every iteration.
Let’s see an example to understand it better:
“`
//Print numbers from 1 to 10 using for loop
for(int i=1; i<=10; i++){
System.out.println(i);
}
“`
This for loop initializes the integer variable i to 1, checks the condition if i is less than or equal to 10, and increments i by 1 after each iteration. The code inside the loop prints the current value of i.
The while loop in Java
The while loop is used when we want to execute a block of code repeatedly as long as a condition is true. The syntax of the while loop is as follows:
“`
while(condition){
//code to be executed
}
“`
Here, the code block will continue to execute until the condition becomes false.
Let’s see an example to understand it better:
“`
//Print numbers from 1 to 10 using while loop
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
“`
Here, the variable i is initialized to 1 and the code inside the while loop prints the value of i and increments it by 1 after each iteration. The while loop continues to execute until i is less than or equal to 10.
The do while loop in Java
The do while loop is used when we want to execute a block of code at least once, irrespective of whether the condition is true or false. The syntax of the do while loop is as follows:
“`
do{
//code to be executed
}while(condition);
“`
Here, the code block will execute at least once before checking the condition. If the condition is true, the code block will execute again.
Let’s see an example to understand it better:
“`
//Print numbers from 1 to 10 using do while loop
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
“`
Here, the variable i is initialized to 1 and the code inside the loop prints the value of i and increments it by 1 after each iteration. Since the condition is checked after executing the code block, the loop executes at least once even if i is greater than 10.
Conclusion
In conclusion, for, while, and do while loops are essential constructs in Java programming. It’s crucial to understand their syntax and working to use them appropriately in our code. By using loops, we can write more efficient code that eliminates redundancy and automates repetitive tasks.