# Loop
A programming construct that repeats a sequence of instructions until a specific condition is met.
**Pronunciation:** /luːp/
**Difficulty:** Beginner
**Synonyms:** Iteration, Repetition
**Categories:** Programming Concepts, Control Flow
**Tags:** iteration, control structure, repetition, programming, algorithm
Canonical: https://scaleengineer.com/glossaries/loop
---
## Definitions

- **Loop in Programming:** In computer programming, a **loop** is a control flow statement that allows code to be executed repeatedly. It's a fundamental concept for performing repetitive tasks without writing the same code multiple times. A synonym for this process is **iteration**.

### Key Concepts
*   **Initialization**: Setting up a counter or condition before the loop starts.
*   **Condition**: A boolean expression that is checked before (or after) each **iteration**. The loop continues as long as the condition is true.
*   **Iteration**: A single execution of the block of code inside the loop.
*   **Update/Increment/Decrement**: Modifying the loop control variable, often to move closer to the termination condition.

### Common Types of Loops
*   **For Loop**: Typically used when the number of iterations is known beforehand. It combines initialization, condition, and update in a single line.
    ```javascript
    // Example in JavaScript
    for (let i = 0; i < 5; i++) {
      console.log("This is iteration number " + i);
    }
    ```
*   **While Loop**: Executes a block of code as long as a specified condition is true. The condition is checked *before* each iteration.
    ```python
    # Example in Python
    count = 0
    while count < 5:
      print(f"The count is {count}")
      count += 1
    ```
*   **Do-While Loop**: Similar to a while loop, but the condition is checked *after* the block of code is executed. This guarantees the loop body runs at least once.
    ```csharp
    // Example in C#
    int n = 0;
    do {
      Console.WriteLine($"Value of n: {n}");
      n++;
    } while (n < 5);
    ```
*   **For-Each Loop (or Enhanced For Loop)**: Used to iterate over the elements of a collection (like an array or list) without needing to manage an index.
    ```java
    // Example in Java
    String[] names = {"Alice", "Bob", "Charlie"};
    for (String name : names) {
      System.out.println(name);
    }
    ```

### Infinite Loops
An infinite loop is a loop that runs forever because its terminating condition is never met. This is usually a bug caused by a logical error.
```javascript
// WARNING: Infinite loop example
while (true) {
  console.log("This will run forever!");
}
```

## Etymology

The term 'loop' in computing is metaphorical, derived from the physical shape of a loop, which suggests a path that returns to its starting point. The concept existed in early mechanical calculating devices, but the term became common with the advent of electronic computers and their flowcharts, where a repeating process would be drawn as a loop.

## First used

1940s

## Historical context

The idea of repeating a set of operations is fundamental to computation. Ada Lovelace, in her notes on Charles Babbage's Analytical Engine in the 1840s, described how the machine could repeat a series of calculations, a concept now recognized as a loop. Early electronic computers in the 1940s, like the ENIAC, required physical rewiring to change programs, but the concept of stored-program computers, developed by John von Neumann and others, made software loops possible. The first high-level programming languages, such as Fortran (1957) with its `DO` loop, and ALGOL (1958) with its more flexible `for` loop, formalized the concept and made it a cornerstone of structured programming. The `while` loop and `do-while` loop structures were later popularized by languages like C, providing even more control over the **repetition** of code blocks.

## Q&A

- **What are the three essential parts of a typical `for` loop structure?:** Initialization (e.g., `let i = 0`), Condition (e.g., `i < 10`), and Update/Increment (e.g., `i++`).
- **What is the main difference between a `while` loop and a `do-while` loop?:** A `while` loop checks its condition *before* executing its code block, so it might not run at all. A `do-while` loop checks its condition *after* executing its code block, guaranteeing it runs at least once.
- **When would you prefer a `for-each` loop over a traditional `for` loop?:** A `for-each` loop is preferred when you need to iterate over all elements of a collection (like an array or list) and you don't need to know the index of the current element.

## Usage examples

- To process every item in the shopping cart, the programmer wrote a `for` **loop** that iterates through the array of products.
- The game server uses a `while` **loop** to continuously listen for incoming player connections until the server is shut down.
- Be careful with your exit condition, or you might create an infinite **loop** that crashes the application.
- The **iteration** process is controlled by the **loop**'s conditional statement.

## Related terms

- Control Flow
- Conditionals
- Recursion
- Algorithm
- Data Structures

## Popular related terms

- For Loop
- While Loop
- Iteration
- Recursion
