Here are 12 problems, from beginner to advanced, on branching with if and switch statements. Write your code in the browser and press "Check": it is run with real gcc on several inputs to see whether the output is correct.
Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.
Positive" if it is positive, "Negative" if it is negative, and "Zero" if it is 0."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
if … else if … else. Check n > 0 and then n < 0; if neither is true, it is 0.#include <stdio.h> int main(void) { int n; scanf("%d", &n); if (n > 0) { printf("Positive\n"); } else if (n < 0) { printf("Negative\n"); } else { printf("Zero\n"); } return 0; }
if statements would also work, but chaining them with else if makes it clear that exactly one of them runs. Be careful: writing the comparison with 0 as if (n = 0) is an assignment — n is overwritten with 0 and the condition is always false (comparison is ==).N is even" if it is even or "N is odd" if it is odd (with the input value in place of N). Note that negative numbers are also given."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
n % 2, is 0, the number is even. If you test for odd with n % 2 == 1, it fails for negative numbers.#include <stdio.h> int main(void) { int n; scanf("%d", &n); if (n % 2 == 0) { printf("%d is even\n", n); } else { printf("%d is odd\n", n); } return 0; }
% gives a negative remainder too: −3 % 2 is −1. So if you test for odd with if (n % 2 == 1), −3 is judged "even". Testing "is it 0?" works correctly regardless of the sign.Larger: value". If the two are equal, print "Same value"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
a == b first and handle the equal case, then split the rest with a > b.#include <stdio.h> int main(void) { int a, b; scanf("%d %d", &a, &b); if (a == b) { printf("Same value\n"); } else if (a > b) { printf("Larger: %d\n", a); } else { printf("Larger: %d\n", b); } return 0; }
if (a > b) … else …, equal values go to the else branch and "Larger: 5" is printed. Which side the equal case (the boundary) belongs to is something to think about every time you write a condition.Valid score" if it is between 0 and 100 inclusive, and "Out of range" otherwise."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
&&. You cannot write 0 <= n <= 100.#include <stdio.h> int main(void) { int n; scanf("%d", &n); if (n >= 0 && n <= 100) { printf("Valid score\n"); } else { printf("Out of range\n"); } return 0; }
0 <= n <= 100 is interpreted as (0 <= n) <= 100. The result of 0 <= n is 0 or 1, and comparing that with 100 is always true, so both 101 and −1 become "valid" (some compilers warn about this). Always write ranges with &&.Grade: S": S for 90 or more, A for 80 or more, B for 70 or more, C for 60 or more, and D for less than 60."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
if (n >= 90) … else if (n >= 80) … — you don't need to write two conditions such as "80 or more and less than 90".#include <stdio.h> int main(void) { int n; scanf("%d", &n); char grade; if (n >= 90) { grade = 'S'; } else if (n >= 80) { grade = 'A'; } else if (n >= 70) { grade = 'B'; } else if (n >= 60) { grade = 'C'; } else { grade = 'D'; } printf("Grade: %c\n", grade); return 0; }
else if (n >= 80), "less than 90" is already certain, so you don't need to add n < 90. Conversely, if you put n >= 60 first, even 100 gets a C. The tests at exactly 90 and 60 catch mix-ups between > and >=."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
a into a variable max first, replace it if b is larger, replace it if c is larger… Comparing one at a time like this saves you from thinking about combinations.#include <stdio.h> int main(void) { int a, b, c; scanf("%d %d %d", &a, &b, &c); int max = a, min = a; if (b > max) max = b; if (c > max) max = c; if (b < min) min = b; if (c < min) min = c; printf("Max: %d\n", max); printf("Min: %d\n", min); return 0; }
else (because you always want to check both b and c). If you write combinations such as if (a > b && a > c), it is easy to make the mistake where, when there are equal values like 7 7 1, none of the conditions match. If you start max at 0, you get 0 when all the numbers are negative.Y is a leap year" if it is a leap year, or "Y is a common year" otherwise. A leap year is "a year divisible by 4, except years divisible by 100, except that years divisible by 400 are leap years"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
&& and ||, add parentheses.#include <stdio.h> #include <stdbool.h> int main(void) { int y; scanf("%d", &y); bool leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; if (leap) { printf("%d is a leap year\n", y); } else { printf("%d is a common year\n", y); } return 0; }
bool variable (<stdbool.h>), you can write the readable if (leap). && has higher precedence than ||, so the meaning is the same without parentheses, but adding parentheses for the reader is recommended.Month M has 30 days". If M is not between 1 and 12, print "Invalid month". Use a switch statement."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
case 4: case 6: case 9: case 11:. Anything other than 1–12 is handled by default.#include <stdio.h> int main(void) { int m; scanf("%d", &m); int days; switch (m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 4: case 6: case 9: case 11: days = 30; break; case 2: days = 28; break; default: printf("Invalid month\n"); return 0; } printf("Month %d has %d days\n", m, days); return 0; }
A: Rock B: Scissors", and on the second line print one of "A wins", "B wins" or "Draw"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
(a - b + 3) % 3, 0 means a draw, 2 means A wins, and 1 means B wins.#include <stdio.h> void print_hand(int h) { switch (h) { case 0: printf("Rock"); break; case 1: printf("Scissors"); break; case 2: printf("Paper"); break; } } int main(void) { int a, b; scanf("%d %d", &a, &b); printf("A: "); print_hand(a); printf(" B: "); print_hand(b); printf("\n"); int r = (a - b + 3) % 3; if (r == 0) { printf("Draw\n"); } else if (r == 2) { printf("A wins\n"); } else { printf("B wins\n"); } return 0; }
+ 3, the remainder is negative when a − b is negative (e.g. −1 % 3 is −1), and the result is off. If you haven't learned functions yet, it is fine to write the switch twice inside main.7 / 2) and print the result in the form "7 / 2 = 3". There are 5 operators, + - * / %, and / and % are C's integer division and remainder. If the right-hand side of / or % is 0, print "Error: division by zero"; for any other operator, print "Error: unknown operator" (the integers are between −10000 and 10000)."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
switch (op), comparing against character constants like case '+':. Inside the cases for / and %, check b == 0 first.#include <stdio.h> int main(void) { int a, b; char op; scanf("%d %c %d", &a, &op, &b); int result; switch (op) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': case '%': if (b == 0) { printf("Error: division by zero\n"); return 0; } result = (op == '/') ? a / b : a % b; break; default: printf("Error: unknown operator\n"); return 0; } printf("%d %c %d = %d\n", a, op, b, result); return 0; }
%c, as in " %c" (here "%d %c %d"), means "skip any whitespace, then read one character". Without the space, the space after the number would be stored in op.Not a triangle". If they can, print "Equilateral triangle" for an equilateral triangle, "Isosceles triangle" for an isosceles triangle, "Right triangle" for a right triangle, and "Ordinary triangle" if it is none of these. For an equilateral triangle, print only "Equilateral triangle". Three sides form a triangle when "the sum of any two sides is longer than the remaining side"."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
a*a + b*b == c*c with ||.#include <stdio.h> int main(void) { int a, b, c; scanf("%d %d %d", &a, &b, &c); if (a + b <= c || b + c <= a || c + a <= b) { printf("Not a triangle\n"); } else if (a == b && b == c) { printf("Equilateral triangle\n"); } else if (a == b || b == c || c == a) { printf("Isosceles triangle\n"); } else if (a * a + b * b == c * c || b * b + c * c == a * a || c * c + a * a == b * b) { printf("Right triangle\n"); } else { printf("Ordinary triangle\n"); } return 0; }
2 5 2 has two equal sides, but 2 + 2 < 5, so it is not a triangle. If you don't check whether it is a triangle first, "Isosceles triangle" is printed by mistake. Likewise, an equilateral triangle also satisfies the isosceles condition, so check the stricter condition (equilateral) first. a == b == c means (a == b) == c, so write it with && (because the sides are integers, an isosceles right triangle never appears in this problem).The first date is earlier" if the first one comes first, "The second date is earlier" if the second one comes first, and "Same date" if they are the same."Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
|| and &&.#include <stdio.h> int main(void) { int y1, m1, d1, y2, m2, d2; scanf("%d %d %d", &y1, &m1, &d1); scanf("%d %d %d", &y2, &m2, &d2); if (y1 == y2 && m1 == m2 && d1 == d2) { printf("Same date\n"); } else if (y1 < y2 || (y1 == y2 && m1 < m2) || (y1 == y2 && m1 == m2 && d1 < d2)) { printf("The first date is earlier\n"); } else { printf("The second date is earlier\n"); } return 0; }
y1 <= y2 && m1 <= m2 && d1 <= d2, 2023/12/31 vs 2024/1/1 is judged wrong because its month and day are larger. Comparing a smaller unit only when the larger units are equal is called lexicographic comparison. Another approach is to turn each date into a single integer, y * 10000 + m * 100 + d, and compare those.