In programming, there are three main types of loops used to repeat a set of instructions:
1. **For Loop**:
- This loop is used when you know in advance how many times you want to execute a statement or a block of statements.
- Syntax (in most languages like Python, C++, etc.):
```python
for i in range(start, end, step):
# code to execute
```
- Example:
```python
for i in range(1, 6):
print(i)
```
This prints numbers from 1 to 5.
2. **While Loop**:
- A while loop repeats a block of code as long as a condition is true. It's useful when you donβt know beforehand how many times the loop will run, and you need to repeat until a specific condition is met.
- Syntax:
```python
while condition:
# code to execute
```
- Example:
```python
i = 1
while i <= 5:
print(i)
i += 1
```
This also prints numbers from 1 to 5.
3. **Do-While Loop** (not in all languages, like Python, but present in languages like C/C++):
- This loop executes the code at least once before checking the condition. After that, it repeats as long as the condition is true.
- Syntax (in languages like C/C++):
```c
do {
// code to execute
} while (condition);
```
- Example:
```c
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
```
This prints numbers from 1 to 5, but the code inside the loop runs at least once, even if the condition is false initially.
So, the three loops are:
- **For loop**: When the number of iterations is known.
- **While loop**: When the number of iterations is not known and depends on a condition.
- **Do-while loop**: Similar to while but ensures the loop runs at least once.
Let me know if you need examples in any specific language!