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 codewhile (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 codedo {
// 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 codefor (initialization; condition; iteration) {
// Code to be executed
}
Here are some examples to demonstrate each loop:
while
loop example:javaCopy codeint count = 1;
while (count <= 5) {
System.out.println("Iteration " + count);
count++;
}
Output:
Copy codeIteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
do-while
loop example:javaCopy codeint count = 1;
do {
System.out.println("Iteration " + count);
count++;
} while (count <= 5);
Output:
Copy codeIteration 1 Iteration 2 Iteration 3 Iteration 4 Iteration 5
for
loop example:javaCopy codefor (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
Output:
Copy codeIteration 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.
Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.
Comments: 0