Java Loops Explained: For, While, and Do-While

 

Loops are used to repeat tasks in programming. Java has three main loops:


1. For Loop

Used when you know how many times to repeat.

for(int i = 1; i <= 5; i++) { System.out.println("Iteration: " + i); }

2. While Loop

Repeats until a condition becomes false.

int i = 1; while(i <= 5) { System.out.println("Iteration: " + i); i++; }

3. Do-While Loop

Executes at least once, then checks the condition.

int i = 1; do { System.out.println("Iteration: " + i); i++; } while(i <= 5);

Tips:

  • Avoid infinite loops by updating your counter or condition.

  • Choose for if count is known, while if unknown, and do-while if at least one execution is needed.


Practice:

Create a loop to print numbers 1–10 or loop through an array of your favorite foods.

Comments

Popular posts from this blog

Welcome to FuadCode – Learn Java Programming from Scratch

Introduction to Java Methods and Functions