For and While Loops
Introduction
In Solidity 0.8.16, you can use loops to execute a block of code repeatedly. There are two types of loops in Solidity: for
and while
. In this blog post, we will explain how to use for
and while
loops in Solidity 0.8.16.
For Loops
A for
loop is used to execute a block of code a specific number of times. Here is an example of a for
loop:
pragma solidity 0.8.16;
contract Example {
function loop(uint n) public pure returns (uint) {
uint sum = 0;
for (uint i = 0; i < n; i++) {
sum += i;
}
return sum;
}
}
In this example, we have defined a function called loop()
that takes an unsigned integer n
as input and returns the sum of the numbers from 0 to n - 1
. The for
loop iterates n
times and adds the current value of i
to the sum
variable.
While Loops
A while
loop is used to execute a block of code repeatedly while a condition is true. Here is an example of a while
loop:
pragma solidity 0.8.16;
contract Example {
function loop(uint n) public pure returns (uint) {
uint sum = 0;
uint i = 0;
while (i < n) {
sum += i;
i++;
}
return sum;
}
}
In this example, we have defined a function called loop()
that takes an unsigned integer n
as input and returns the sum of the numbers from 0 to n - 1
. The while
loop iterates while i
is less than n
and adds the current value of i
to the sum
variable. The i
variable is incremented after each iteration.
Gas Fees and Alternatives to Looping
It's important to note that loops can be expensive in terms of gas fees. Each iteration of a loop costs a certain amount of gas, which can add up quickly if the loop is executed many times. Therefore, it's important to consider alternative approaches to looping if possible.
Conclusion
In this blog post, we explained how to use for
and while
loops in Solidity 0.8.16. for
loops are used to execute a block of code a specific number of times, while while
loops are used to execute a block of code repeatedly while a condition is true. By using loops in your Solidity code, you can perform repetitive tasks efficiently and effectively.
Feedback
Have feedback? Found something that needs to be updated, accurate, or explained?
Join our discord and share what can be improved.
Any and all feedback is welcomed.