0Pricing
Blockchain Smart Contracts with Solidity · Aula

Estruturas de controle e loops

Domine instruções condicionais (if/else) e diferentes estruturas de repetição (for, while) para criar comportamentos dinâmicos em contratos.

Estruturas de controle e loops é uma aula grátis de Blockchain Smart Contracts with Solidity no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Blockchain Smart Contracts with Solidity, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Control Structures Intro

Bem-vindo à Lição 2! Hoje, aprenderemos sobre estruturas de controle em Solidity. Elas são essenciais para tornar seus contratos inteligentes dinâmicos e responsivos.

As estruturas de controle permitem que seu contrato:

  • Tome decisões com base em condições.
  • Repita ações várias vezes.
  • Execute diferentes caminhos de código.

Pense nelas como o 'cérebro' do seu contrato, guiando seu comportamento.

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!

Perguntas Frequentes

A aula “Estruturas de controle e loops” é grátis?

Sim — o texto completo de “Estruturas de controle e loops” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Blockchain Smart Contracts with Solidity, atualize para CoddyKit PRO. O curso de Blockchain Smart Contracts with Solidity inclui 4 aulas no total.

O que vou aprender em “Estruturas de controle e loops”?

Domine instruções condicionais (if/else) e diferentes estruturas de repetição (for, while) para criar comportamentos dinâmicos em contratos. Você pratica Blockchain Smart Contracts with Solidity com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Blockchain Smart Contracts with Solidity?

Nenhuma experiência prévia é necessária. Blockchain Smart Contracts with Solidity no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “Estruturas de controle e loops”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Blockchain Smart Contracts with Solidity?

Sim. Cada aula de Blockchain Smart Contracts with Solidity inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Tipos de dados e variáveis em Solidity
  2. Estruturas de controle e loops
  3. Funções e modificadores de visibilidade
  4. Structs e Enums
← Voltar para Blockchain Smart Contracts with Solidity