C Conditional Exercises (if & switch)

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.

How to use these problems
  1. Read the problem and the sample run, then write your code in the box
  2. Press "▶ Run" to try it with your own input
  3. Press "✔ Check" to test the output against several prepared inputs
  4. Stuck? Open "Hint". Solved it? Compare with "Solution & explanation"
Checking rules
  • Print output exactly as in the sample run. Do not print input prompts such as "Enter a number"
  • Trailing spaces at line ends and trailing blank lines are ignored
  • Your code is saved automatically in this browser

Note: Run and Check send your code to Wandbox, a free external compiler service, and run it with gcc.

12 problems (Beginner 4 · Intermediate 5 · Advanced 3)

if & switch (12 problems)

I01 Beginner

Problem 1. Positive, negative or zero

Read an integer N (−10000 ≤ N ≤ 10000) and print "Positive" if it is positive, "Negative" if it is negative, and "Zero" if it is 0.
Sample run (input is underlined)
-3 Negative
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
There are three cases, so use 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;
}
Explanation: Three separate 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 ==).
I02 Beginner

Problem 2. Even or odd

Read an integer N (−10000 ≤ N ≤ 10000) and print "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.
Sample run (input is underlined)
7 7 is odd
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
If the remainder when divided by 2, 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;
}
Explanation: In C, when the number being divided is negative, % 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.
I03 Beginner

Problem 3. The larger of two numbers

Read two integers a and b separated by a space and print the larger value as "Larger: value". If the two are equal, print "Same value".
Sample run (input is underlined)
3 7 Larger: 7
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
It is easiest to check 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;
}
Explanation: With only two branches, 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.
I04 Beginner

Problem 4. Score range check

Read an integer x and print "Valid score" if it is between 0 and 100 inclusive, and "Out of range" otherwise.
Sample run (input is underlined)
101 Out of range
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
It is "at least 0 and at most 100", so join the two comparisons with logical AND, &&. 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;
}
Explanation: 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 &&.
I05 Intermediate

Problem 5. Grading

Read a score (an integer from 0 to 100) and print the grade as "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.
Sample run (input is underlined)
85 Grade: A
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
If you line them up from the highest score down — 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;
}
Explanation: else if checks from the top and runs only the first branch that is true. By the time you reach 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 >=.
I06 Intermediate

Problem 6. Maximum and minimum of three numbers

Read three integers a, b and c separated by spaces and print the maximum and the minimum.
Sample run (input is underlined)
3 9 2 Max: 9 Min: 2
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Put 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;
}
Explanation: The key here is to write independent ifs without 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.
I07 Intermediate

Problem 7. Leap year check

Read a year Y (1 ≤ Y ≤ 9999) and print "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".
Sample run (input is underlined)
2024 2024 is a leap year
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Combined into one expression with logical operators, the condition is "(divisible by 4 and not divisible by 100) or divisible by 400". When you mix && 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;
}
Explanation: With only "divisible by 4 means leap year", you get 1900 and 2100 wrong. If you store the result of the condition in a 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.
I08 Intermediate

Problem 8. Days in a month (switch)

Read a month M as an integer and print the number of days in that month in a common year (February has 28 days) as "Month M has 30 days". If M is not between 1 and 12, print "Invalid month". Use a switch statement.
Sample run (input is underlined)
4 Month 4 has 30 days
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Months with the same number of days can be grouped by stacking cases, like 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;
}
Explanation: A switch runs the statements in order from the matching case up to a break. Using this, you can stack cases with no statements to say "if it matches any of these, do the same thing". Conversely, if you forget a break, execution continues into the next case after April, so be careful.
I09 Intermediate

Problem 9. Rock-paper-scissors

Read the hands of A and B as integers separated by a space (0: rock, 1: scissors, 2: paper). On the first line print both hands, like "A: Rock B: Scissors", and on the second line print one of "A wins", "B wins" or "Draw".
Sample run (input is underlined)
0 1 A: Rock B: Scissors A wins
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
You can print the name of a hand with a switch statement. You may write out all 9 outcomes, but if you compute (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;
}
Explanation: The hands are ordered rock (0) → scissors (1) → paper (2) → rock so that each hand beats the one whose number is one larger, which means the remainder of the difference a − b divided by 3 decides the result. If you forget the + 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.
I10 Advanced

Problem 10. A simple calculator

Read an expression of the form "integer operator integer" (e.g. 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).
Sample run (input is underlined)
7 / 2 7 / 2 = 3
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Branch on the operator character with 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;
}
Explanation: Dividing by 0 is undefined behavior and may even crash the program, so check before dividing. In scanf, putting a space before %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.
I11 Advanced

Problem 11. Classifying triangles

Read three side lengths a, b and c (integers from 1 to 1000, in any order). If they cannot form a triangle, print "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".
Sample run (input is underlined)
5 3 4 Right triangle
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
The order of the checks matters. Chain them with else if in this order: (1) can it form a triangle → (2) are all three sides equal → (3) are two sides equal → (4) is it a right triangle. Because the order of the sides is not fixed, join the three versions of 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;
}
Explanation: 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).
I12 Advanced

Problem 12. Which date comes first

Read two dates as "year month day", one per line (both are real dates). Print "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.
Sample run (input is underlined)
2024 3 15 2024 3 20 The first date is earlier
Your code
"Run" executes your code with the input above. "Check" tests it against 5 prepared inputs.
Compare year → month → day in that order. "The year is smaller, or the year is the same and the month is smaller, or the year and month are the same and the day is smaller" can be written as one condition with || 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;
}
Explanation: If you compare each field separately, as in 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.

Review these lessons

← Back to all practice problems