In programming, a
loop is a way to repeat a set of instructions or code multiple times until a certain condition is met. Loops are useful when you need to perform repetitive tasks without writing the same code again and again.
There are different types of loops, but the most common ones are:
- For Loop: Runs a specific number of times.
- Example: If you want to print numbers from 1 to 5, a
for loop
will repeat the print statement five times.
`
python
for i in range(1, 6):
print(i)
`
Output:
`
1
2
3
4
5
`
- While Loop: Continues to run as long as a given condition is true.
- Example: If you want to print numbers starting from 1 until you reach 5, a
while loop
will keep running as long as the condition (i <= 5) is true.
`
python
i = 1
while i <= 5:
print(i)
i += 1
`
- Do-While Loop (in some languages like C or Java): The condition is checked after the code runs, so the loop runs at least once.
In simple terms, think of a loop like a conveyor belt: it keeps doing the same task (like moving items) until a condition tells it to stop.