2️⃣

4.2 For Loop

4.2 For Loop

For loops run a block of code for based on a condition that is updated at every iteration of the loop.

Basic Structure

This is what a typical for loop looks like:
for (statement 1; statement 2; statement 3) { // code that runs }

Statement 1: Initialization

This executes just ONCE before the execution of the code in the for statement.

Statement 2: Condition

This is the condition that is checked before the execution of the code in the for loop.

Statement 3: Iterator

This is executed every time the code in the for loop finished.

Example

Here's an example of a for loop:
let total = 0; for (int i = 0; i < 5; i++) { // 0 + 1 + 2 + 3 + 4 total += i; } // total = 10
You don't always need to include statement 1 or 3. You DO need a statement 2. So, this is allowed:
let i = 0; let total = 0; for (; i < 5;) { // 0 + 1 + 2 + 3 + 4 total += i; i++; }

Practice

You can add practice problems here if you want. Follow the format below.
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.