Introduction to Java · Introduction to Java Programming

For Loop

1. When to Use (beginner)

For = counting loop — best when rounds known (1 to 10, array elements). Packs init, check, update in one line so you never forget update (unlike while!).

2. Anatomy (read the one line!)

for (int i = 1; i <= 5; i++) { // init; check; update
    System.out.print(i + " "); // 1 2 3 4 5
}
// i dies here (scoped to loop!)

Variants exam loves:

for (int i = 5; i >= 1; i--) System.out.print(i + " "); // 5 4 3 2 1 (reverse!)
int sum = 0;
for (int i = 1; i <= 100; i++) sum += i; // 5050 (Gauss!)
for (int i = 0; i < arr.length; i++) System.out.println(arr[i]); // array walk
for (int x : arr) System.out.println(x); // for-each (simpler, no index!)

3. For vs While (exam table)

for while
Best for known rounds unknown rounds
Parts one line (; ;) scattered (forget update → infinite!)
Scope i dies after i lives on

4. Traps

  • for(;;) = infinite (empty = always true!). for(int i=0; i<5; i--) = infinite down-up bug.
  • Off-by-one: < arr.length (not <= — else ArrayIndexOutOfBounds!).
  • ; after for(...); = empty loop (body runs once with final i!).

5. Exam Points

  • Table/star pattern with nested for — 7 marks, all-time favourite.
  • Trace + off-by-one + for-each — 3-5 marks, frequent.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules