Loops Java Notes
Loops Java Notes
Each loop type has its own strengths and should be chosen based
on the problem you're solving. The for loop is usually best when
you know how many times you need to iterate, while the while
and do-while loops are ideal when the loop count depends on
some runtime condition.
2. while Loop
The while loop is used when you don't know the number of
iterations in advance but want to loop based on a condition.
Structure:
while (condition) {
// Code to be executed
int i = 1;
while (i <= 5) {
System.out.println(i);
Explanation:
The loop starts with i = 1.
It checks if i <= 5. If true, it prints the value of i and increments
i.
The loop continues until i becomes greater than 5.
3. do-while Loop
The do-while loop is like the while loop but guarantees that the loop body
will execute at least once, regardless of the condition. The condition is
checked after executing the loop body.
Structure:
do {
// Code to be
executed
} while (condition);
int i = 1;
do {
System.out.println(i);
Explanation:
The loop starts with i = 1 and prints the value of i before checking
the condition.
After printing, it increments i and checks if i <= 5.
The loop continues until i becomes greater than 5.
A Short Guide to Java Loops
In Java, loops are used to execute a block of code repeatedly until a
certain condition is met. There are three primary types of loops:
1. for loop
2. while loop
3. do-while loop
1. for Loop
The for loop is typically used when the number of iterations is known
beforehand. It has the following structure:
// Code to be executed
System.out.println(i);
Explanation: