If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Java, loop statements allow you to execute a block of code repeatedly based on a certain condition. There are three types of loop statements in Java:
while loop:
while loop repeatedly executes a block of code as long as the given condition is true. It checks the condition before each iteration.javaCopy code
while (condition) {
// Code to be executed
}
do-while loop:
do-while loop is similar to the while loop, but it checks the condition after each iteration. This guarantees that the block of code is executed at least once.javaCopy code
do {
// Code to be executed
} while (condition);
for loop:
for loop is typically used when you know the number of iterations in advance. It consists of three parts: initialization, condition, and iteration expression, separated by semicolons.javaCopy code
for (initialization; condition; iteration) {
// Code to be executed
}
Here are some examples to demonstrate each loop:
while loop example:javaCopy code
int count = 1;
while (count <= 5) {
System.out.println("Iteration " + count);
count++;
}
Output:
Copy code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
do-while loop example:javaCopy code
int count = 1;
do {
System.out.println("Iteration " + count);
count++;
} while (count <= 5);
Output:
Copy code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
for loop example:javaCopy code
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
Output:
Copy code
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
Loop statements are powerful tools for automating repetitive tasks and iterating over data structures such as arrays and collections. They are commonly used in programming to make code more efficient and concise.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support