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.)
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.
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.
#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.
Common mistakes
- Use
==to compare;=assigns (andif (x = 5)is always true). - Forgetting
break;makes a case fall through into the next one. Leave it out only on purpose, as whencase 10:shares the code ofcase 9:.
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.
if / else if / else
Las condiciones se evalúan de arriba hacia abajo; se ejecuta el primer bloque verdadero.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
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.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
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.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
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.
Haz clic en Ejecutar para ver la salida aquí.