For and While Loops in Java
Loops in Java are control structures that allow repeated execution of a block of code as long as a specified condition is true. The two most common types are for loops and while loops.
For Loop
A for loop is typically used when the number of iterations is known. Its syntax is:
$$ \text{for (initialization; condition; update) {\\ \quad \text{// code \to execute}\\ }} $$
- Initialization: Sets up a loop control variable.
- Condition: Checked before each iteration; loop continues if true.
- Update: Changes the loop control variable after each iteration.
- The condition is checked before each iteration.
- The loop continues as long as the condition is true.
- Use a for loop when the number of iterations is known.
- Use a while loop when the number of iterations is unknown or depends on a condition.
- Both loops repeatedly execute code as long as their condition is true.
While Loop
A while loop is used when the number of iterations is not known in advance. Its syntax is:
$$ \text{while (condition) {\\ \quad \text{// code \to execute}\\ }} $$
Worked Example
Problem: Print the numbers from 1 to 5 using both a for loop and a while loop.
For Loop:
```java
for (int i = 1; i 5$
**While Loop:**
```java
\int i = 1;
while (i 5$