0
0
Blockchain / Solidityprogramming~5 mins

For and while loops in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Loops help you repeat actions many times without writing the same code again and again.

When you want to check every item in a list of transactions.
When you need to count how many blocks have been added to the chain.
When you want to repeat a task until a certain condition is met, like waiting for a payment confirmation.
When you want to process each user in a group one by one.
When you want to keep trying an action until it succeeds.
Syntax
Blockchain / Solidity
for (initialization; condition; update) {
    // code to repeat
}

while (condition) {
    // code to repeat
}

The for loop repeats code a set number of times.

The while loop repeats code as long as a condition is true.

Examples
This for loop prints numbers 0 to 4.
Blockchain / Solidity
for (let i = 0; i < 5; i++) {
    console.log(i);
}
This while loop prints the count until it reaches 3.
Blockchain / Solidity
let count = 0;
while (count < 3) {
    console.log('Count is ' + count);
    count++;
}
Sample Program

This program shows how to use both for and while loops to process blocks numbered 1 to 3.

Blockchain / Solidity
function processBlocks() {
    console.log('Processing blocks with for loop:');
    for (let block = 1; block <= 3; block++) {
        console.log(`Block number ${block} processed.`);
    }

    console.log('Processing blocks with while loop:');
    let block = 1;
    while (block <= 3) {
        console.log(`Block number ${block} processed.`);
        block++;
    }
}

processBlocks();
OutputSuccess
Important Notes

Make sure the loop condition will eventually become false, or the loop will run forever.

Use for loops when you know how many times to repeat.

Use while loops when you repeat until a condition changes.

Summary

Loops repeat code to save time and avoid mistakes.

for loops are for counting or fixed repeats.

while loops run while a condition is true.