While Loops
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 32 of 53.
A while loop checks a condition and repeats its body while that condition is true. You control the update inside the body. Make sure the loop changes something that can eventually make its condition false.
The statements in this excerpt run inside the provided main function.
uint256 remaining = 3;
while (remaining > 0) {
console.log(remaining);
remaining--;
}The counter is printed before it is decreased. When it reaches zero, the next condition check stops the loop, so unsigned subtraction never runs at zero. A missing decrement would leave the condition true forever.
A while loop needs a path that eventually makes its condition false.
Challenge
EasyStarting at n, print a countdown to 1 using while, then print stop. n is between 0 and 7.
The tests pass arguments to main in this order: uint256 n. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 n) external view {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground