In Java, you can use for loops to execute a block of code repeatedly for a fixed number of times. Here's an example:
publicclassForLoopExample{publicstaticvoidmain(String[]args){for(int i =1; i <=5; i++){System.out.println(i);}}}
In the above example, we use a for loop to print the numbers from 1 to 5. The loop starts with an initial value of i equal to 1, and executes as long as i is less than or equal to 5. The loop increments i by 1 after each iteration, using the i++ shorthand for i = i + 1.
You can also use it for loops with arrays, like this:
publicclassArrayLoopExample{publicstaticvoidmain(String[]args){int[] numbers ={1,2,3,4,5};for(int i =0; i <numbers.length; i++){System.out.println(numbers[i]);}}}
In the above example, we use a for loop to iterate over an array of numbers. The loop starts with an initial value of i equal to 0, and executes as long as i is less than the length of the numbers array. The loop increments i by 1 after each iteration.
While loops
In Java, you can use while loops to execute a block of code repeatedly as long as a certain condition is true. Here's an example:
In the above example, we use a while loop to print the numbers from 1 to 5. The loop starts with an initial value of i equal to 1, and executes as long as i is less than or equal to 5. The loop increments i by 1 after each iteration.
You can also use while loops with boolean variables, like this:
In the above example, we use a while loop to print the numbers from 1 to 5, but we use a boolean variable keepGoing to control the loop instead of a numeric condition. The loop starts with an initial value of keepGoing equal to true, and executes as long as keepGoing is true. The loop sets keepGoing to false when i equals 5, causing the loop to exit.
Do-while loops
In Java, you can use do-while loops to execute a block of code repeatedly at least once, and then as long as a certain condition is true. Here's an example:
In the above example, we use a do-while loop to print the numbers from 1 to 5. The loop starts by executing the block of code once and then continues to execute as long as i is less than or equal to 5. The loop increments i by 1 after each iteration.
Do-while loops are useful when you need to execute a block of code at least once, regardless of the condition.
That's an overview of loops, while loops, and do-while loops in Java.
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
}
}
public class BooleanLoopExample {
public static void main(String[] args) {
boolean keepGoing = true;
int i = 1;
while (keepGoing) {
System.out.println(i);
if (i == 5) {
keepGoing = false;
}
i++;
}
}
}
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}