for Loop
A for loop repeats a block of code a specific number of times. It combines initialization, a condition, and an update step, all in one compact line.
1. What is a for Loop?
A for loop repeats a block of code a specific number of times. It combines initialization, a condition, and an update step, all in one compact line.
2. Why is it used?
Many tasks need repetition with a known count — like printing numbers from 1 to 10, or going through every item in a list. The for loop handles this kind of repetition cleanly.
3. Real-Life Example
Think of a teacher calling out roll numbers from 1 to 40 one by one during attendance. There's a clear starting point, an ending point, and a fixed step (increase by 1 each time) — exactly how a for loop works.
4. Syntax
javafor (initialization; condition; update) { // code to repeat }
5. Example Program
javapublic class ForLoopDemo { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); } } }
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 56. Key Points to Remember
- The three parts (initialization, condition, update) are all optional individually, but the two semicolons are always required.
- The loop keeps running as long as the condition remains true.
- A missing or wrong update step can cause an infinite loop.