Selection and iteration · Seleção e iteração
| English | Português |
|---|---|
| selection/sɪˈlekʃn/ | seleção |
| iteration/ˌɪtəˈreɪʃn/ | iteração |
| trace table/treɪs ˈteɪbl/ | tabela de traçagem |
| nested/ˈnestɪd/ | aninhado |
| logic error/ˈlɒdʒɪk ˈerə/ | erro de lógica |
| count-controlled loop/kaʊnt kənˈtrəʊld luːp/ | laço controlado por contagem |
| array/əˈreɪ/ | array (matriz/lista) |
| pre-condition loop/priː kənˈdɪʃn luːp/ | pré-condição do laço |
| post-condition loop/pəʊst kənˈdɪʃn luːp/ | pós-condição do laço |
| dry run/draɪ rʌn/ | execução seca |
One line too many
- In 2014 Apple shipped a security update because of a single repeated line. Deep inside the code that checked a website's certificate,
goto fail;appeared twice in a row. - The second copy sat outside its
IF, so it ran every time, and the check below it never did. For months, any attacker could pretend to be any website. - Selection and iteration are the constructs that decide what runs and how often. Get one line of them wrong and the program still runs, just wrongly.
- This lesson is IF, CASE and the three loops, and the trace table that catches the mistake before the exam does.
Uma linha a mais
- Em 2014, a Apple enviou uma atualização de segurança devido a uma única linha repetida. Profundamente dentro do código que verificava o certificado de um site,
goto fail;apareceu duas vezes seguidas. - A segunda cópia ficava fora do seu
IF, então executava sempre, e a verificação abaixo dela nunca fazia. Por meses, qualquer atacante podia fingir ser qualquer site. - Seleção e iteração são as construções que decidem o que executa e com que frequência. Errar uma linha delas e o programa ainda roda, apenas errado.
- Esta lição é sobre IF, CASE e os três loops, e a tabela de traço que pega o erro antes do exame o faça.
Selection
IF age >= 18 THEN … ELSE … ENDIF
- The
ELSEis optional, theENDIFis not. EveryIFmust be closed. - A condition is any Boolean expression: a comparison, or comparisons joined by
AND,ORandNOT.
An IF … ELSE tests once, then runs exactly one branch
Seleção
IF age >= 18 THEN … SENÃO … FIM_SE
- O
ELSEé opcional, oENDIFnão é. TodoIFdeve ser fechado. - Uma condição é qualquer expressão Boolean: uma comparação, ou comparações unidas por
AND,OReNOT.

Um IF … ELSE testa uma vez, então executa exatamente um ramo
Nested IFs and boundaries
- A nested 嵌套 IF is an IF inside a branch of another IF, and each one needs its own
ENDIF. - Boundaries are where marks are lost. "A mark of 50 or more passes" is
Mark >= 50, notMark > 50. - A wrong comparison is a logic error 逻辑错误: the program runs and gives the wrong answer for some inputs. A trace with the boundary value, 50 itself, is how you find it.
IFs aninhados e limites
- Um IF aninhado 嵌套 é um IF dentro de um ramo de outro IF, e cada um precisa do seu próprio
ENDIF. - Limites são onde pontos são perdidos. "Uma nota de 50 ou mais passa" é
Mark >= 50, nãoMark > 50. - Uma comparação errada é um erro lógico 逻辑错误: o programa roda e dá a resposta errada para algumas entradas. Um traço com o valor limite, 50 próprio, é como você o encontra.
"A mark of 50 or more passes" is written as IF Mark ____ 50 THEN. · "Uma nota de 50 ou mais passa" é escrito como IF Mark ____ 50 THEN.
"Or more" includes 50 itself, so the comparison is greater than or equal. > would fail a student on exactly 50. · "Ou mais" inclui 50 em si, então a comparação é maior ou igual. > falharia um aluno com exatamente 50.
CASE
CASE OF Grade … ENDCASEtests one value against several options and is cleaner than a chain of nested IFs.- A guard can be a single value
"A":, a list1, 2, 3:, or a range1 TO 5:. The last branch for "anything else" isOTHERWISE, never a condition such as> 200. - Guards are tested in order. With
1 TO 50:followed by40 TO 60:, a value of 45 takes the first branch, so an assignment in the second may never run. If the earlier branches cover every possible value,OTHERWISEis never performed either.
A CASE runs the first branch whose guard matches the value
CASE
CASE OF Grade … ENDCASEtesta um valor contra várias opções e é mais limpo do que uma cadeia de IFs aninhados.- Um guard pode ser um único valor
"A":, uma lista1, 2, 3:, ou um intervalo1 TO 5:. O último ramo para "qualquer outra coisa" éOTHERWISE, nunca uma condição como> 200. - Guardas são testados em ordem. Com
1 TO 50:seguido por40 TO 60:, um valor de 45 toma o primeiro ramo, então uma atribuição no segundo pode nunca ser executada. Se os ramos anteriores cobrirem todos os valores possíveis,OTHERWISEtambém nunca é realizado.

Um CASE executa o primeiro ramo cujo guard corresponde ao valor
A CASE statement is cleaner than nested IFs when you are: · Uma instrução CASE é mais limpa que IFs aninhados quando você está:
CASE matches one value against many possibilities; deep nested IFs become hard to read. · CASE combina um valor contra muitas possibilidades; IFs profundos aninhados tornam-se difíceis de ler.
Which of these are valid guards in a Cambridge CASE statement? Select all · todos that apply. · Quais destes são guarda válidos em uma instrução CASE da Cambridge? Selecione todas as opções.
A single value, a value list, a range and OTHERWISE. A comparison such as > 200 is not a guard; anything not covered goes to OTHERWISE. · Um único valor, uma lista de valores, um intervalo e OTHERWISE. Uma comparação como > 200 não é um guarda; tudo o que não for coberto vai para O/CASE.
Worked example: rewrite a CASE without a CASE
CASE OF MySwitchwith1: ThisChar ← 'a',2: ThisChar ← 'y',3: ThisChar ← '7',OTHERWISE: ThisChar ← '*'.- Each value becomes one branch of a chain of IFs, and
OTHERWISEbecomes the finalELSE.
- Three IFs, three ENDIFs. Going the other way, two CASE clauses that assign the same value merge into one guard with a value list,
1, 2:.
Exemplo resolvido: reescreva um CASE sem um CASE
CASE OF MySwitchcom1: ThisChar ← 'a',2: ThisChar ← 'y',3: ThisChar ← '7',OTHERWISE: ThisChar ← '*'.- Cada valor torna-se um ramo de uma cadeia de IFs, e
OTHERWISEtorna-se o finalELSE.
IF MySwitch = 1 THEN
ThisChar <- 'a'
ELSE
IF MySwitch = 2 THEN
ThisChar <- 'y'
ELSE
IF MySwitch = 3 THEN
ThisChar <- '7'
ELSE
ThisChar <- '*'
ENDIF
ENDIF
ENDIF
- Três IFs, três ENDIFs. Indo na outra direção, dois clauses CASE que atribuem o mesmo valor fundem-se em um guard com uma lista de valores,
1, 2:.
The three loops
- Iteration 迭代 repeats a block, and the three loops differ in where the condition is tested.
- A count-controlled loop 计数循环,
FOR i ← 1 TO 10 … NEXT i, runs a known number of times;STEP -1counts down. Use it for a fixed count or every element of an array 数组. - A pre-condition loop 前测循环,
WHILE … DO … ENDWHILE, tests before each pass, so it may run zero times. A post-condition loop 后测循环,REPEAT … UNTIL, tests after each pass, so it always runs at least once.
Where the condition sits decides how many times the body can run
Os três loops
- Iteração 迭代 repete um bloco, e os três loops diferem em onde a condição é testada.
- Um loop controlado por contagem 计数循环,
FOR i ← 1 TO 10 … NEXT i, roda um número conhecido de vezes;STEP -1conta para baixo. Use-o para uma contagem fixa ou cada elemento de um array 数组. - Um loop de pré-condição 前测循环,
WHILE … DO … ENDWHILE, testa antes de cada passagem, então pode rodar zero vezes. Um loop de pós-condição 后测循环,REPEAT … UNTIL, testa depois de cada passagem, então sempre roda pelo menos uma vez.

Onde a condição está decide quantas vezes o corpo pode rodar
Match each loop to when you'd use it. · Combine cada laço com quando você o usaria.
FOR = count-controlled; WHILE = condition tested before (0+ passes); REPEAT = condition tested after (1+ passes). · FOR = controlado por contagem; WHILE = condição testada antes (0+ passagens); REPEAT = condição testada depois (1+ passagens).
REPEAT...UNTIL tests its condition AFTER the body, so the body always runs at least once. · REPEAT...UNTIL testa sua condição DEPOIS do corpo, então o corpo sempre executa pelo menos uma vez.
That post-condition test is the difference from WHILE, which can run zero times. · Esse teste pós-condição é a diferença em relação ao WHILE, que pode executar zero vezes.
Choosing the loop: the two-mark answer
- One mark for the name, one for the reason, in the scheme's words.
- Count-controlled, because the number of iterations is known before the loop starts. Post-condition, because the loop body must be executed at least once. Pre-condition, because the loop may not need to execute at all.
- A loop over the four elements of an array written as a
WHILEwith a counter is "not the most appropriate"; the FOR loop is, because the count is known.
Escolhendo o loop: a resposta de dois pontos
- Um ponto para o nome, um para o motivo, nas palavras do gabarito.
- Controlado por contagem, porque o número de iterações é conhecido antes do loop começar. Pós-condição, porque o corpo do loop deve ser executado pelo menos uma vez. Pré-condição, porque o loop pode não precisar executar de todo.
- Um loop sobre os quatro elementos de um array escrito como um
WHILEcom um contador é "não o mais apropriado"; o loop FOR é, porque a contagem é conhecida.
A question asks you to "identify a more appropriate loop and justify your choice" for 2 marks. What earns the two marks? · Uma pergunta pede para "identificar um laço mais apropriado e justificar sua escolha" por 2 marks. O que vale as duas marks?
One mark for the loop, one for the reason: the count is known, the body must run once, or the loop may not run at all. · Uma mark para o laço, uma para o motivo: a contagem é conhecida, o corpo deve rodar uma vez, ou o laço pode não rodar nada.
Worked example: which loop fits each task?
- Print the 12 times table: the count is known in advance, so a FOR loop.
- Keep reading numbers until the user enters 0: the count is unknown and the very first input might already be 0, so the test must come before the body: a WHILE loop.
- Ask for a password until it is correct: the user must be asked at least once, so a REPEAT … UNTIL loop.
- Ask two questions: how many times, and must the body run before the first test?
Exemplo resolvido: qual loop se adapta a cada tarefa?
- Imprima a tabela de multiplicar 12: a contagem é conhecida antecipadamente, então um loop FOR.
- Continue lendo números até que o usuário insira 0: a contagem é desconhecida e a primeira entrada pode já ser 0, então o teste deve vir antes do corpo: um loop WHILE.
- Solicitar uma senha até que esteja correta: o usuário deve ser perguntado pelo menos uma vez, portanto um laço REPEAT … UNTIL.
- Fazer duas perguntas: quantas vezes e o corpo deve rodar antes do primeiro teste?
"Keep asking for a password until it is correct, but always ask at least once." Which loop fits? · "Siga pedindo uma senha até que esteja correta, mas sempre peça pelo menos uma vez." Qual laço se encaixa?
You must ask at least once, so the post-condition REPEAT...UNTIL is the natural choice. · Você deve pedir pelo menos uma vez, então o REPEAT...UNTIL pós-condição é a escolha natural.
Trace tables
- A trace table 跟踪表 records every variable's value as you dry run 手工跟踪 the algorithm by hand. It is how a loop is tested on paper and a six-mark question on most Paper 2s.
- One column per variable, plus a column for any output. Write a new row only when a value changes, and evaluate the loop condition at the moment the loop reaches it.
- Keep going until the condition ends the loop, then record the final output.
Tabelas de traçagem
- Uma tabela de traçagem 跟踪表 registra o valor de cada variável enquanto você faz dry run 手工跟踪 o algoritmo manualmente. É como testar um laço no papel e uma questão de seis pontos na maioria dos Paper 2s.
- Uma coluna por variável, mais uma coluna para qualquer saída. Escreva uma nova linha apenas quando um valor mudar, e avalie a condição do laço no momento em que o laço chegar a ela.
- Continue até que a condição termine o laço, então registre a saída final.
Trace a loop, pass by pass · Rastreie um laço, passagem por passagem
A trace table records each variable after every pass of the loop. Watch the counter i climb while the running total builds up — exactly what an exam trace question asks you to fill in. · Uma tabela de rastro registra cada variável após cada passagem do laço. Observe o contador i subir enquanto o total acumulado se constrói — exatamente o que uma questão de rastro de exame pede para preencher.
After total = 0; FOR i = 1 TO 5: total = total + i, what is the value of total? · Depois de total = 0; FOR i = 1 TO 5: total = total + i, qual é o valor de total?
Adding 1+2+3+4+5 = 15 — exactly what the trace table builds up pass by pass. · Somando 1+2+3+4+5 = 15 — exatamente o que a tabela de traçação acumula passagem por passagem.
Worked example: a trace table filled
- Rows of (Count, Total): (1, 0) → (2, 1) → (3, 3) → (4, 6) → (5, 10).
- At Total = 10 the condition
Total < 10is false, the loop ends, and the output is 5. - The last row is the one most often wrong: check the condition one more time before writing the output.
Exemplo resolvido: uma tabela de traçagem preenchida
Count <- 1
Total <- 0
WHILE Total < 10 DO
Total <- Total + Count
Count <- Count + 1
ENDWHILE
OUTPUT Count
- Linhas de (Count, Total): (1, 0) → (2, 1) → (3, 3) → (4, 6) → (5, 10).
- Em Total = 10 a condição
Total < 10é falsa, o laço termina e a saída é 5. - A última linha é a mais frequentemente errada: verifique a condição mais uma vez antes de escrever a saída.
In the worked trace, the loop ends with Total = 10 and Count = 5, so the output is 5. · Na traçação resolvida, o laço termina com Total = 10 e Count = 5, então a saída é 5.
After the fourth pass Total reaches 10, the condition Total < 10 becomes false, and Count has been incremented to 5. · Após a quarta passagem, Total atinge 10, a condição Total < 10 torna-se falsa, e Count foi incrementado para 5.
Marks that slip away
>=and>are different answers. Test the boundary value in your head before you write the comparison.OTHERWISEis a keyword, not a condition. And everyIF,CASE,WHILEandFORcloses withENDIF,ENDCASE,ENDWHILEorNEXT.- A
WHILEcan run zero times; aREPEATcannot. Choose by whether the body must run once before the first test. - In a trace table, a value that does not change is not rewritten, and the output is written only when the
OUTPUTline runs.
Marcas que escapam
>=e>são respostas diferentes. Teste o valor limite mentalmente antes de escrever a comparação.OTHERWISEé uma palavra-chave, não uma condição. E todoIF,CASE,WHILEeFORfecha comENDIF,ENDCASE,ENDWHILEouNEXT.- Um
WHILEpode rodar zero vezes; umREPEATnão pode. Escolha dependendo se o corpo precisa rodar uma vez antes do primeiro teste. - Em uma tabela de traçagem, um valor que não muda não é reescrito, e a saída é escrita apenas quando a linha do
OUTPUTroda.
You've got it
- IF … ELSE … ENDIF for a choice; nested IFs each closed; CASE for one value against many guards, tested in order,
OTHERWISElast - FOR count known · WHILE tests before, may run zero times · REPEAT … UNTIL tests after, runs at least once
- justify a loop with its name and reason: known count, may not run, must run once
- a trace table dry-runs the algorithm one row per change; check the condition once more before the final output
Entendeu?
- IF … ELSE … ENDIF para uma escolha; IFs nested aninhados fechados; CASE para um valor contra muitos guardas, testados em ordem,
OTHERWISEpor último - FOR count conhecido · WHILE testa antes, pode rodar zero vezes · REPEAT … UNTIL testa depois, roda pelo menos uma vez
- justifique um laço com seu nome e razão: conta conhecida, pode não rodar, deve rodar uma vez
- uma tabela de traçagem faz dry-run do algoritmo uma linha por mudança; verifique a condição mais uma vez antes da saída final