Control Structures

Control Structures

Beginner Level

Like traditional programming languages, Solidity supports conditional statements (if-else), loops (for, while, do-while), and the ternary operator for concise decisions. Although Solidity does not have a switch statement, developers can simulate switch-like logic using if-else blocks or mappings.

1. If-else Statements

The if-else structure is used for decision-making. It executes different blocks of code depending on whether a condition evaluates to true or false.

Example (Grading system):


pragma solidity ^0.8.0;

contract IfElseExample {
    function getGrade(uint256 score) public pure returns (string memory) {
        if (score >= 90) {
            return "A";
        } else if (score >= 75) {
            return "B";
        } else if (score >= 50) {
            return "C";
        } else {
            return "F";
        }
    }
}

Here, depending on the score, the function returns different grades.

2. Loops (for, while, do-while)

Loops allow us to repeat code execution until a condition is met. In Solidity, excessive looping should be avoided because loops consume gas. Always use them with caution.

a) For Loop

Used when the number of iterations is known.


pragma solidity ^0.8.0;

contract ForLoopExample {
    function sumNumbers(uint256 n) public pure returns (uint256) {
        uint256 sum = 0;
        for (uint256 i = 1; i <= n; i++) {
            sum += i;
        }
        return sum;
    }
}

If n = 5, the function returns 15 (1 + 2 + 3 + 4 + 5).

b) While Loop

Executes as long as the condition is true.


pragma solidity ^0.8.0;

contract WhileLoopExample {
    function factorial(uint256 n) public pure returns (uint256) {
        uint256 result = 1;
        while (n > 0) {
            result *= n;
            n--;
        }
        return result;
    }
}

If n = 4, the function returns 24 (4 × 3 × 2 × 1).

c) Do-While Loop

Similar to while, but executes at least once, even if the condition is false.


pragma solidity ^0.8.0;

contract DoWhileExample {
    function countdown(uint256 start) public pure returns (uint256) {
        uint256 counter = start;
        do {
            counter--;
        } while (counter > 0);
        return counter; // always returns 0
    }
}

Even if start = 1, the loop runs once before checking the condition.

3. Switch-like Logic in Solidity

Since Solidity does not have a switch statement, developers can simulate it using if-else chains or mappings.

a) If-else Simulation


pragma solidity ^0.8.0;

contract SwitchLikeIfElse {
    function getDay(uint256 dayNumber) public pure returns (string memory) {
        if (dayNumber == 1) return "Monday";
        else if (dayNumber == 2) return "Tuesday";
        else if (dayNumber == 3) return "Wednesday";
        else if (dayNumber == 4) return "Thursday";
        else if (dayNumber == 5) return "Friday";
        else if (dayNumber == 6) return "Saturday";
        else if (dayNumber == 7) return "Sunday";
        else return "Invalid day";
    }
}

Acts like a switch-case for days of the week.

b) Mapping-based Simulation

Mappings are more efficient when you have many fixed options.


pragma solidity ^0.8.0;

contract SwitchLikeMapping {
    mapping(uint256 => string) public dayName;

    constructor() {
        dayName[1] = "Monday";
        dayName[2] = "Tuesday";
        dayName[3] = "Wednesday";
        dayName[4] = "Thursday";
        dayName[5] = "Friday";
        dayName[6] = "Saturday";
        dayName[7] = "Sunday";
    }

    function getDay(uint256 dayNumber) public view returns (string memory) {
        return bytes(dayName[dayNumber]).length > 0
            ? dayName[dayNumber]
            : "Invalid day";
    }
}

Uses a mapping to store and retrieve values efficiently, like a switch table.

4. Ternary Operator

The ternary operator is a short form of if-else. It is written as:

condition ? valueIfTrue : valueIfFalse

Example (Even or Odd Check):


pragma solidity ^0.8.0;

contract TernaryExample {
    function checkEvenOdd(uint256 num) public pure returns (string memory) {
        return num % 2 == 0 ? "Even" : "Odd";
    }
}

If num = 4, it returns "Even". If num = 7, it returns "Odd".

Summary

Control Structure Purpose Example Use
if-else Conditional logic Grading system
for loop Iterates fixed times Summation
while loop Iterates until condition fails Factorial
do-while loop Executes at least once Countdown
switch-like (if-else) Multi-option branching Day of week
switch-like (mapping) Efficient key-value lookup Day of week storage
ternary operator Concise if-else Even/Odd check

Continue Learning

Explore more topics in Solidity or browse other tutorials.