Algoritmos e lógica de programação com Portugol Studio - Condicionais - ESCOLHA-CASO [ Vídeo 8.1 ]
Table of Contents
Introduction
This tutorial focuses on the conditional structure ESCOLHA-CASO (SWITCH-CASE) in programming using Portugol Studio. Understanding this structure is essential for making decisions in your algorithms based on various conditions. This guide will walk you through the concept and provide practical examples to help you implement this in your programs.
Step 1: Understanding the ESCOLHA-CASO Structure
The ESCOLHA-CASO structure allows you to execute different code blocks based on the value of a variable. It simplifies complex conditional statements by avoiding multiple if-else statements.
Key Features
- Evaluates a single expression against a list of possible values.
- Executes the code block corresponding to the matching value.
- Can include a default case to handle unexpected values.
Step 2: Syntax of ESCOLHA-CASO
Familiarize yourself with the basic syntax:
ESCOLHA (expression)
CASO value1:
// Code block for value1
CASO value2:
// Code block for value2
...
CASO OUTRO:
// Default code block
FIMESCOLHA
Explanation of Syntax Components
- expression: The variable or value being evaluated.
- value1, value2: The specific cases to match against the expression.
- OUTRO: Represents the default case if none of the previous cases match.
Step 3: Implementing an Example
Let’s create a simple program that demonstrates the ESCOLHA-CASO structure to determine the day of the week based on a number input.
Example Code
algoritmo "Dia da Semana"
var
dia: inteiro
inicio
escreva("Digite um número de 1 a 7: ")
leia(dia)
ESCOLHA (dia)
CASO 1:
escreva("Domingo")
CASO 2:
escreva("Segunda-feira")
CASO 3:
escreva("Terça-feira")
CASO 4:
escreva("Quarta-feira")
CASO 5:
escreva("Quinta-feira")
CASO 6:
escreva("Sexta-feira")
CASO 7:
escreva("Sábado")
CASO OUTRO:
escreva("Número inválido. Digite um número de 1 a 7.")
FIMESCOLHA
fimalgoritmo
Explanation of the Example
- The program prompts the user to enter a number between 1 and 7.
- It uses the ESCOLHA-CASO structure to print the corresponding day of the week.
- If the input is outside the specified range, it outputs an invalid number message.
Step 4: Common Pitfalls
- Ensure that your expression matches the type of cases you define.
- Always include a default case (OUTRO) to handle unexpected inputs.
- Be mindful of the order of cases; the first match will execute, and subsequent cases will be ignored.
Conclusion
The ESCOLHA-CASO structure in Portugol Studio is a powerful tool for managing multiple conditions in your algorithms. By mastering this concept, you can simplify your code and create more readable programs. As a next step, practice implementing this structure in various scenarios, such as menu selections or grading systems, to solidify your understanding.