0Pricing
Blockchain Smart Contracts with Solidity · 강의

제어 구조와 반복문

동적인 계약 동작을 구현하기 위해 조건문(if/else)과 다양한 반복문(for, while) 구문을 익힙니다.

제어 구조와 반복문은(는) CoddyKit의 무료 Blockchain Smart Contracts with Solidity 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Blockchain Smart Contracts with Solidity 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Control Structures Intro

Welcome to Lesson 2! Today, we'll learn about control structures in Solidity. These are essential for making your smart contracts dynamic and responsive.

Control structures allow your contract to:

  • Make decisions based on conditions.
  • Repeat actions multiple times.
  • Execute different code paths.

Think of them as the 'brain' of your contract, guiding its behavior.

Conditional 'if' Statements

The simplest control structure is the if statement. It executes a block of code only if a specified condition is true.

The condition must evaluate to a bool (true or false). If true, the code inside the curly braces {} runs; otherwise, it's skipped.

'if-else' for Alternatives

Often, you want to perform one action if a condition is true and a different action if it's false. This is where the if-else statement comes in.

If the if condition is true, its block executes. If false, the code in the else block executes instead. Only one of the two blocks will ever run.

'else if' for Multiple Choices

What if you have more than two possible outcomes? Use else if to check multiple conditions sequentially.

The contract checks each condition in order. The first one that evaluates to true will have its code block executed, and all subsequent else if and else blocks are skipped.

Conditional Logic Example

Let's see if-else if-else in action. This contract checks if a number is positive, negative, or zero.

Try calling checkNumber with different integer values like 5, -3, or 0.

pragma solidity ^0.8.0;

contract ConditionalChecker {
    function checkNumber(int _number) public pure returns (string memory) {
        if (_number > 0) {
            return "Positive";
        } else if (_number < 0) {
            return "Negative";
        } else {
            return "Zero";
        }
    }
}

Introducing Loops

Sometimes you need to repeat a block of code multiple times. This is called looping, and it's super efficient!

Loops are useful for:

  • Iterating over arrays or lists.
  • Performing calculations multiple times.
  • Waiting for a condition to be met.

Solidity provides for and while loops.

The 'for' Loop

The for loop is perfect when you know exactly how many times you want to repeat an action. It has three parts:

  • Initialization: Sets up a counter (e.g., uint i = 0).
  • Condition: The loop continues as long as this is true (e.g., i < 10).
  • Increment/Decrement: Changes the counter after each iteration (e.g., i++).

Runnable 'for' Loop

Here's a for loop example that calculates the sum of numbers up to a given limit. This shows how to accumulate a value over several iterations.

Try calling calculateSum with a small number like 5.

pragma solidity ^0.8.0;

contract ForLoopDemo {
    // Calculates the sum of numbers from 1 up to _limit
    function calculateSum(uint _limit) public pure returns (uint) {
        uint total = 0;
        for (uint i = 1; i <= _limit; i++) {
            total += i;
        }
        return total;
    }
}

The 'while' Loop

The while loop is ideal when you don't know exactly how many times the loop needs to run, but you have a specific condition that must be met to stop.

The loop continues as long as its condition is true. Be careful to ensure the condition eventually becomes false to avoid infinite loops!

Runnable 'while' Loop

This example demonstrates a simple countdown using a while loop. The loop continues as long as currentCount is greater than zero.

Call simpleCountdown with a value like 3. It will return 0 after completing the countdown.

pragma solidity ^0.8.0;

contract WhileLoopDemo {
    // Counts down from a starting number to zero
    function simpleCountdown(uint _start) public pure returns (uint) {
        uint currentCount = _start;
        while (currentCount > 0) {
            currentCount--; // Decrement counter
        }
        return currentCount; // Will be 0 when loop finishes
    }
}

Check Your Understanding

Consider the following Solidity contract function:

pragma solidity ^0.8.0;

contract ScoreChecker {
    function getStatus(uint _score) public pure returns (string memory) {
        if (_score >= 90) {
            return "Excellent";
        } else if (_score >= 70) {
            return "Good";
        } else if (_score >= 50) {
            return "Pass";
        } else {
            return "Fail";
        }
    }
}

Recap: Control & Loops

Great job! You've mastered the fundamentals of control structures and loops in Solidity.

  • Conditional statements (if, else if, else) allow your contract to make decisions.
  • Loops (for, while) enable repetitive execution of code blocks.

These tools are crucial for building smart contracts that can react dynamically and perform complex operations. Next, we'll dive into functions and visibility modifiers!

자주 묻는 질문

“제어 구조와 반복문” 강의는 무료인가요?

네 — “제어 구조와 반복문” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Blockchain Smart Contracts with Solidity 강의 전체를 잠금 해제할 수 있습니다. Blockchain Smart Contracts with Solidity 강의에는 총 4개의 강의가 포함되어 있습니다.

“제어 구조와 반복문”에서 뭘 배우나요?

동적인 계약 동작을 구현하기 위해 조건문(if/else)과 다양한 반복문(for, while) 구문을 익힙니다. 브라우저에서 직접 실행하는 실습 코드로 Blockchain Smart Contracts with Solidity을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Blockchain Smart Contracts with Solidity을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Blockchain Smart Contracts with Solidity은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“제어 구조와 반복문” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Blockchain Smart Contracts with Solidity 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Blockchain Smart Contracts with Solidity 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Solidity 데이터 형식과 변수
  2. 제어 구조와 반복문
  3. 함수와 가시성 지정자
  4. 구조체와 열거형
← Blockchain Smart Contracts with Solidity(으)로 돌아가기