Loop
A loop is a control structure that repeats a block of code multiple times until a condition is met. It allows programs to perform repetitive tasks automatically.
Why loops are important
Many tasks require repetition.
For example:
- Display numbers from 1 to 100
- Process every item in a list
- Repeat an action until the user quits
Without loops, you would have to write the same code many times.
How a loop works
A loop usually has:
- A starting point
- A condition
- A repeating action
- A stopping point
The loop continues running while the condition is true.
Common Types of Loops
1. For Loop
Used when the number of repetitions is known.
Example:
2. While Loop
Used when repetition depends on a condition.
Example:
The loop runs until the condition becomes false.
3. Do-While Loop
Executes the code at least once before checking the condition.
Example:
Infinite Loop
If the stopping condition never becomes false, the loop runs forever.
Example:
This is called an infinite loop.
Why learning loops matters
Variables represent locations in computer memory.
Loops help you:
- Automate repetitive tasks
- Work with large data sets
- Improve code efficiency
- Build dynamic programs
They are essential for real-world programming.
Simple example
Think of brushing your teeth:
Repeat brushing until your teeth are clean.
That is a loop controlled by a condition.
Related terms
- What is Condition?
- What is Boolean?
- What is Variable?
Source
Simplified from general programming documentation and Wikipedia.