Today you will learn:
for loopswhile loopsdo-while loopsbreak and continueBy the end, you will be able to repeat tasks automatically using loops.
The for loop is used when you know how many times to repeat something.
for(int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
Explanation:
int i = 1 → start valuei <= 5 → conditioni++ → incrementThe while loop runs as long as a condition is true.
int i = 1;
while(i <= 5) {
System.out.println("Number: " + i);
i++;
}
The do-while loop always runs at least once.
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while(i <= 5);
Stops the loop completely.
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break;
}
System.out.println(i);
}
Skips the current iteration.
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue;
}
System.out.println(i);
}
for(int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
Print all even numbers from 1 to 50 using a loop.
Steps:
%Example:
public class EvenNumbers {
public static void main(String[] args) {
for(int i = 1; i <= 50; i++) {
if(i % 2 == 0) {
System.out.println(i);
}
}
}
}