Java for Loop
A loop repeats a block of code. Use the for loop when you know how many times to repeat.
Syntax
for (initialization; condition; update) {
// code to repeat
}
- Initialization runs once at the start.
- The condition is checked before every round. If it is false, the loop ends.
- The update runs after every round.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Round " + i);
}
}
}
Output
Round 1
Round 2
Round 3
Round 4
Round 5
Different steps
public class Steps {
public static void main(String[] args) {
for (int i = 0; i <= 20; i += 5) {
System.out.print(i + " ");
}
System.out.println();
for (int i = 5; i >= 1; i--) { // count down
System.out.print(i + " ");
}
System.out.println();
}
}
Output
0 5 10 15 20
5 4 3 2 1
Sum of numbers
public class Sum {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum 1 to 100 = " + sum);
}
}
Output
Sum 1 to 100 = 5050
Nested loops
public class Table {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Enhanced for loop (for each)
The easy way to go through all the items of an array or a collection:
public class Each {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "mango"};
for (String fruit : fruits) {
System.out.println(fruit);
}
int[] marks = {70, 85, 90};
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Total: " + total);
}
}
Output
apple
banana
mango
Total: 245
Use the normal for loop when you need the index. Use the for each loop when you only need the values.
Loop variable scope
A variable declared in the for line (like i) exists only inside the loop.
Infinite loop
If the condition is always true, the loop never stops. This is sometimes used on purpose, with a break inside:
for (;;) {
// runs for ever, until break
}
Note:
Be careful about off by one errors: i < 5 runs 5 times from 0 to 4, while i <= 5 runs 6 times. Next: Java while and do while Loop.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |