Lesson 06 of 25
Control Flow
if/else, for loops, while loops, and break/continue in smart contracts.
BeginnerConditionals
Solidity control flow is identical to JavaScript/C. Use
if, else if, and else for branching logic. The ternary operator is also supported.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Conditionals {
function classify(uint256 n) public pure returns (string memory) {
if (n == 0) {
return "zero";
} else if (n < 10) {
return "small";
} else if (n < 100) {
return "medium";
} else {
return "large";
}
}
// Ternary operator
function isEven(uint256 n) public pure returns (bool) {
return n % 2 == 0 ? true : false;
}
}
For Loops
for loops work the same as in C/JavaScript. Be careful: unbounded loops can run out of gas if the array grows too large!
Solidity
contract Loops {
function sumArray(uint256[] memory arr)
public pure returns (uint256 total)
{
for (uint256 i = 0; i < arr.length; i++) {
total += arr[i];
}
// Named return — automatically returns `total`
}
function findIndex(uint256[] memory arr, uint256 target)
public pure returns (int256)
{
for (uint256 i = 0; i < arr.length; i++) {
if (arr[i] == target) return int256(i);
}
return -1; // not found
}
}
While & Do-While
Use
while when the number of iterations is unknown. do-while always executes at least once.
Solidity
contract WhileDemo {
function collatz(uint256 n) public pure returns (uint256 steps) {
while (n != 1) {
if (n % 2 == 0) {
n = n / 2;
} else {
n = 3 * n + 1;
}
steps++;
}
}
}
Break & Continue
break exits a loop early. continue skips to the next iteration. Use these to write cleaner, more gas-efficient loop logic.
Solidity
contract BreakContinue {
// Sum only even numbers, stop at first number > 100
function conditionalSum(uint256[] memory arr)
public pure returns (uint256 total)
{
for (uint256 i = 0; i < arr.length; i++) {
if (arr[i] > 100) break; // exit loop entirely
if (arr[i] % 2 != 0) continue; // skip odd numbers
total += arr[i];
}
}
}