In programming, **loops** are used to repeat a block of code multiple times until a specified condition is met. There are two primary types of loops:
### 1. **For Loop**
A **for loop** is used when you know in advance how many times you want to execute a statement or a block of statements. It is generally used to iterate over a sequence such as a list, tuple, or string, or for executing a fixed number of iterations.
#### Structure (in most languages like Python, C, Java):
```python
for i in range(5): # Python example
print(i)
```
- In this example, the loop runs 5 times, starting from `i = 0` to `i = 4`.
- The loop iterates a fixed number of times (determined by the range), which is ideal when the number of iterations is known beforehand.
#### Common Use Cases:
- Iterating through the elements of a list or array.
- Repeating a task for a fixed number of times (e.g., printing numbers from 1 to 100).
---
### 2. **While Loop**
A **while loop** is used when you want to execute a block of code repeatedly as long as a given condition is true. It’s useful when the number of iterations isn’t known beforehand and depends on dynamic conditions.
#### Structure (in Python or similar languages):
```python
i = 0
while i < 5:
print(i)
i += 1
```
- Here, the loop continues as long as `i` is less than 5. The variable `i` increments with each iteration until the condition is no longer true.
- The loop may run indefinitely if the condition never becomes false (leading to an infinite loop), so it’s crucial to ensure the condition will eventually change.
#### Common Use Cases:
- Continuously checking for user input until valid input is provided.
- Running a task until a specific condition, like a flag, becomes false.
---
### Key Differences:
- **For loops** are ideal when the number of iterations is known or when you are working with a sequence (like lists or arrays).
- **While loops** are better for cases where you need to loop based on a condition that may change during runtime, and you don’t know the number of iterations in advance.
Both types of loops serve different purposes but are fundamental in controlling the flow of a program.