0
0
Blockchain / Solidityprogramming~10 mins

Using for directive in Blockchain / Solidity - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Using for directive
Start
Initialize loop variable
Check loop condition
| Yes
Execute loop body
Update loop variable
Check loop condition
No
End loop
The for directive starts by setting a variable, checks a condition, runs the loop body if true, updates the variable, and repeats until the condition is false.
Execution Sample
Blockchain / Solidity
for (let i = 0; i < 3; i++) {
  console.log(i);
}
This code prints numbers 0, 1, and 2 using a for loop.
Execution Table
IterationiCondition i < 3ActionOutput
10truePrint i=00
21truePrint i=11
32truePrint i=22
43falseExit loop
💡 i reaches 3, condition i < 3 is false, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 2 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at iteration 4 (see execution_table row 4), so the loop exits.
When is the loop variable i updated?
After executing the loop body in each iteration, i is increased by 1 before the next condition check (see variable_tracker changes).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during the third iteration?
A2
B3
C1
D0
💡 Hint
Check the 'i' column in the execution_table at iteration 3.
At which iteration does the loop condition become false?
AIteration 3
BIteration 2
CIteration 4
DIteration 1
💡 Hint
Look at the 'Condition i < 3' column in the execution_table.
If the loop condition changed to i <= 3, how many times would the loop run?
A3 times
B4 times
C2 times
D5 times
💡 Hint
Think about when i <= 3 is true based on variable_tracker values.
Concept Snapshot
for directive syntax:
for (initialization; condition; update) {
  // code to repeat
}

- Initialize variable once
- Check condition before each loop
- Run code if true
- Update variable after each loop
- Repeat until condition false
Full Transcript
The for directive runs a loop by first setting a variable, then checking if it meets a condition. If yes, it runs the loop body, then updates the variable. This repeats until the condition is false, then the loop stops. For example, a loop from 0 to 2 prints 0, 1, 2. The variable i starts at 0 and increases by 1 each time. When i reaches 3, the condition fails and the loop ends.