Thuta Learning
BasicProgrammingbeginner

Loops (For, While)

Relax. We'll talk through this in plain words — no textbook voice.

A loop is a control structure that runs a code block over and over. You need loops to read through a data list, print numbers 1 to 10, tally up cart items, or check through records. Without loops, printing item 100 would mean writing 100 separate lines — great arm workout, terrible developer life.

java
public class Main {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      System.out.println("For loop item: " + i);
    }

    int countdown = 3;
    while (countdown > 0) {
      System.out.println("Countdown: " + countdown);
      countdown--;
    }
  }
}

for loop has three parts: initialization, condition, and update. i <= 5 stays true, it keeps running. while loop checks the condition first, then runs.

You should see
For loop item: 1 For loop item: 2 For loop item: 3 For loop item: 4 For loop item: 5 Countdown: 3 Countdown: 2 Countdown: 1

Real-World Use

Loops are what you use to process database records, product lists, comments, notifications, or report rows one at a time.

Easy traps

  • Forgetting to update the counter inside a while loop is a classic way to end up with a program that never stops.
Loops (For, While) | Thuta Learning