Booleans and selection: if, else, switch · Booleanos y selección: 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.)
Verdadero y falso en C
- C no tiene un tipo separado de verdadero/falso por defecto. Usa números:
0significa falso, y cualquier otro número significa verdadero. - Una prueba como
5 > 3produce1(verdadero).5 < 3produce0(falso). - (Si incluyes
#include <stdbool.h>puedes escribirbool,trueyfalse— perointpuro funciona en todas partes.)
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.
Comparar y combinar
- Compara valores con
==(igual),!=(diferente),<,>,<=,>=. - Ten cuidado:
==prueba igualdad; un único=asigna un valor. ¡Son diferentes! - Combina pruebas con
&&(y),||(o) y!(no).a && bes verdadero solo cuando ambos lo son.
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) { ... }ejecuta el bloque solo cuando la prueba es verdadera.- Añade
else if (...)para verificar otra prueba, yelsepara "ninguna de las anteriores". - Solo se ejecuta la rama que coincide primero.
#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: elegir entre muchos valores
- Un
switchelige una rama basado en un valor (unintochar). - Cada
casetermina conbreak;para no caer en el siguiente.default:captura todo lo demás. switches útil cuando comparas la misma variable contra muchos valores fijos.
Common mistakes
- Use
==to compare;=assigns (andif (x = 5)is always true). - Each
switchcase needs abreak;.
Errores comunes
- Usa
==para comparar;=asigna (yif (x = 5)siempre es verdadero). - Cada caso en un
switchnecesita unbreak;.
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.
Ahora tú intentas
- Usa comparaciones y
&&/||para construir tus pruebas. Recuerda que0es falso, cualquier otra cosa es verdadero. - Para la tarea del
switch, divide la puntuación por 10 primero, luego haz switch sobre el resultado. - No escribas un
main— el verificador proporciona uno.
if / else if / else
Conditions test top-down; the first true block runs. · Las condiciones se evalúan de arriba hacia abajo; se ejecuta el primer bloque verdadero.
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 · no write a main. · Complete int sign(int n) para que devuelva -1 cuando n sea negativo, 0 cuando n sea cero, y 1 cuando n sea positivo. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete int in_range(int n, int lo, int hi) so it returns 1 when n is between lo and · y hi (inclusive), and 0 otherwise. Use &&. Do not · no write a main. · Complete int in_range(int n, int lo, int hi) para que devuelva 1 cuando n esté entre lo y hi (inclusive), y 0 en caso contrario. Use &&. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 · no write a main. · Complete char grade_letter(int score) usando un switch sobre score / 10. Devuelva 'A' para 90–100, 'B' para los 80s, 'C' para los 70s, 'D' para los 60s, y 'F' por debajo de 60. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.