Booleans and selection: if, else, switch · Booleans e seleção: if, else, switch
True and false in C
- C has no separate true/false type by default. It uses numbers:
0means false, and any other number means true. - A test like
5 > 3produces1(true).5 < 3produces0(false). - (If you
#include <stdbool.h>you can writebool,true, andfalse— but plainintworks everywhere.)
Verdadeiro e falso em C
- C não tem um tipo true/false separado por padrão. Usa números:
0significa false, e qualquer outro número significa true. - Um teste como
5 > 3produz1(true).5 < 3produz0(false). - (Se você
#include <stdbool.h>, pode escreverbool,trueefalse— mas ointsimples funciona em todos os lugares.)
Comparing and combining
- Compare values with
==(equal),!=(not equal),<,>,<=,>=. - Be careful:
==tests equality; a single=assigns a value. They are different! - Combine tests with
&&(and),||(or), and!(not).a && bis true only when both are true.
Comparando e combinando
- Compare valores com
==(igual),!=(diferente),<,>,<=,>=. - Tenha cuidado:
==testa igualdade; um único=atribui um valor. Eles são diferentes! - Combine testes com
&&(and),||(or) e!(not).a && bé true apenas quando ambos são true.
if / else if / else
if (test) { ... }runs the block only when the test is true.- Add
else if (...)to check another test, andelsefor "none of the above". - Only the first matching branch runs.
if / else if / else
if (test) { ... }executa o bloco apenas quando o teste é true.- Adicione
else if (...)para verificar outro teste, eelsepara "nenhum dos acima". - Apenas o primeiro ramo correspondente é executado.
#include <stdio.h>
int main(void) {
int score = 72;
if (score >= 90) {
printf("A\n");
} else if (score >= 60) {
printf("Pass\n"); // this one runs
} else {
printf("Fail\n");
}
return 0;
}
switch: choosing among many values
- A
switchpicks a branch based on one value (anintorchar). - Each
caseends withbreak;so it does not fall into the next one.default:catches everything else. switchis neat when you compare the same variable against many fixed values.
switch: escolhendo entre muitos valores
- Um
switchescolhe um ramo baseado em um valor (umintouchar). - Cada
casetermina combreak;para que não caia no próximo.default:pega tudo o mais. switché limpo quando você compara a mesma variável contra muitos valores fixos.
Common mistakes
- Use
==to compare;=assigns (andif (x = 5)is always true). - Each
switchcase needs abreak;.
Erros comuns
- Use
==para comparar;=atribui (eif (x = 5)é sempre true). - Cada caso
switchprecisa de umbreak;.
Now you try
- Use comparisons and
&&/||to build your tests. Remember0is false, anything else is true. - For the
switchtask, divide the score by 10 first, then switch on the result. - Do not write a
main— the checker provides one.
Agora você tenta
- Use comparações e
&&/||para construir seus testes. Lembre-se0é false, qualquer outra coisa é true. - Para a tarefa de
switch, divida a pontuação por 10 primeiro, depois faça switch no resultado. - Não escreva um
main— o verificador fornece um.
if / else if / else
Conditions test top-down; the first true block runs. · Condições são testadas de cima para baixo; o primeiro bloco verdadeiro é executado.
Complete int sign(int n) so it returns -1 when n is negative, 0 when n is zero, and 1 when n is positive. Do not · não write a main. · Complete int sign(int n) para que retorne -1 quando n for negativo, 0 quando n for zero, e 1 quando n for positivo. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int in_range(int n, int lo, int hi) so it returns 1 when n is between lo and · e hi (inclusive), and 0 otherwise. Use &&. Do not · não write a main. · Complete int in_range(int n, int lo, int hi) para que retorne 1 quando n estiver entre lo e hi (inclusive), e 0 caso contrário. Use &&. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete char grade_letter(int score) using a switch on score / 10. Return 'A' for 90–100, 'B' for the 80s, 'C' for the 70s, 'D' for the 60s, and 'F' below 60. Do not · não write a main. · Complete char grade_letter(int score) usando um switch em score / 10. Retorne 'A' para 90–100, 'B' para a faixa dos 80s, 'C' para a faixa dos 70s, 'D' para a faixa dos 60s, e 'F' abaixo de 60. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.