# For...Loop

There is probably a programming language out there that does not have some sort of implementation of the for loop, but they are few and far between. It is almost a requirement in order to have the computer do code repeatedly **a certain number** of times.&#x20;

The loop contains a counter or **index** that the programmer defines. The code will run and loop back to the top as long as the "**continue condition**" is true. Each loop iteration needs to modify the index somehow or else you have an infinite loop. Typically you increase the index by 1 but you can do any sort of mathematical operation on the index.

### Syntax

&#x20;The syntax is fairly simple:

<div align="center"><img src="/files/-LPm8HWLVOdtIUBDwh1v" alt=""></div>

```javascript
for (index start value; continue condition; index modifier) {
    // code
}
```

### Example 1 - [Hello World](https://tech.io/snippet/HU3d1Dk)

```javascript
// The following prints "Hello World!" 5 times, showing the line number
// Start at 1, end before 6 (so, 5), increase by 1 every interation
for ( let index = 1; index < 6; index++ ) {

    console.log(`${index}: Hello world!`);

}
```

### Example 2 - Animation

Here is an animation of a for loop in action. The code prints the powers of 2 from a power of zero to ten (inclusive). It also keeps track of a running total and prints that at the end.

![](/files/-LQRF9dT7G220-aFU38g)

{% hint style="info" %}
For a faster animation, [click here](https://drive.google.com/file/d/0BzyP6cTwQ57eaEFjX2lkdW9zWDQ/view?usp=sharing) (and for a really fast one, [click here](https://drive.google.com/file/d/0BzyP6cTwQ57eaFBIMXAtQ05nYjg/view?usp=sharing)).
{% endhint %}

### Example 3 - [Decrement](https://tech.io/snippet/Ra72fAC)

While most examples and definitions show `i++` to *increment* the index, it does not need to be counting *up.* You can *decrement* (subtract one), add 2, multiply by a value... it all depends on the needs of the programmer. Here is an example of a for loop that counts *down* by 1:

```javascript
// Print from 20 (inclusive) to -10 (exclusive)
// Start at 20, loop if greater than -10 (so stop after -9), decrease by 1 each loop
for (let i = 20; i > -10; i--) {
    console.log(i);
}
```

### Example 4 - [Nested Loops](https://tech.io/snippet/P1NODsX)

Because a for loop can contain any amount of code (scope block `{ }`), you can write *another* for loop inside (and another inside that, etc). This is called *nested looping*. An example would be printing a multiplication table or other 2-dimensional work:

```javascript
// Print the multiplication table from 1 to 10 (inclusive)
let output;

// Rows (1 top, 10 bottom)
for (let y = 1; y <= 10; y++) {
    output = ''; // Make sure it is a string
    
    // Columns (1 left, 10 right)
    for (let x = 1; x <= 10; x++) {
        // Build the output row
        output += x*y + "\t";
    }
    
    // Print the current row
    console.log(output);
}
```

### More Information

#### If you need more information, here are some other sources:

{% embed url="<https://www.khanacademy.org/computing/computer-programming/programming/looping/pt/for-loops-a-new-kind-of-loop>" %}

{% embed url="<https://youtu.be/BxFi7vVZx4s?t=86>" %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.brash.ca/unit-3/loops/for-loop.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
