Skip to content

Part 1 · Lesson 5

Conditional Statements

  • interactive
On this page

What you'll learn: making decisions with if, else and else if chains, and combining conditions with && and ||.

Before you start: Lessons 1-4, especially the operators from Lesson 4.

Our programs so far have been linear; they execute every line of code from top to bottom in the same order every time. To create powerful and intelligent programs, we need them to be able to make decisions.

CONDITIONAL STATEMENTS allow us to control the flow of our program's execution. They use the relational and logical operators from the previous lesson to evaluate conditions. If a condition is true (evaluates to a non-zero value), one block of code is executed. If it's false (evaluates to 0), that block is skipped, and optionally, another block is executed.

The primary tool for this is the if statement.

The if statement is the simplest form of a conditional. It executes a block of code ONLY if its condition is true.

Syntax:

if (condition)
{
    // Code to execute if 'condition' is true
}

For example:

if (score == 100)
{
    printf("Congratulations on a perfect score!\n");
}

The else statement provides an alternative block of code to execute when the if condition is false.

Syntax:

if (condition)
{
    // Code to execute if 'condition' is true
}
else
{
    // Code to execute if 'condition' is false
}

The lesson uses it to tell even numbers from odd ones (remember % from Lesson 4):

if (number_to_check % 2 == 0)
{
    printf("%d is an even number.\n", number_to_check);
}
else
{
    printf("%d is an odd number.\n", number_to_check);
}

To check for multiple, mutually exclusive conditions, you can chain else if statements. The program will check each condition in order. As soon as it finds a true condition, it runs that block and skips the rest of the entire chain. The final else is optional and acts as a "catch-all" if none of the preceding conditions were true.

if (user_grade >= 90)
{
    printf("Your letter grade is A.\n");
}
else if (user_grade >= 80)
{
    printf("Your letter grade is B.\n");
}
else if (user_grade >= 70)
{
    printf("Your letter grade is C.\n");
}
else if (user_grade >= 60)
{
    printf("Your letter grade is D.\n");
}
else
{
    printf("Your letter grade is F.\n");
}

A grade of 85 fails the first test, passes user_grade >= 80, prints "B" and skips everything after it, which is why the >= 70 test never sees it.

Combining Conditions

We can use logical operators (&&, ||) to create more complex conditions. For example, to check if a grade is a B (80-89):

if (user_grade >= 80 && user_grade < 90)
{
    printf("This is a solid B.\n");
}

Full Source

5_conditional_statements.c 181 lines Download View on GitHub
/**
 * @file 5_conditional_statements.c
 * @brief Part 1, Lesson 5: Conditional Statements
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson introduces conditional statements, which allow a program
 * to make decisions and execute different code blocks based on specific conditions.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * Our programs so far have been linear; they execute every line of code from
 * top to bottom in the same order every time. To create powerful and intelligent
 * programs, we need them to be able to make decisions.
 *
 * CONDITIONAL STATEMENTS allow us to control the flow of our program's execution.
 * They use the relational and logical operators from the previous lesson to
 * evaluate conditions. If a condition is true (evaluates to a non-zero value),
 * one block of code is executed. If it's false (evaluates to 0), that block
 * is skipped, and optionally, another block is executed.
 *
 * The primary tool for this is the `if` statement.
 */

#include <stdio.h>

int main(void)
{
    // --- Part 1: The `if` Statement ---

    /*
     * The `if` statement is the simplest form of a conditional. It executes a
     * block of code ONLY if its condition is true.
     *
     * Syntax:
     * if (condition) {
     *     // Code to execute if 'condition' is true
     * }
     */
    int score = 100;

    printf("--- Part 1: The 'if' Statement ---\n");
    printf("Initial score: %d\n", score);

    // This condition `score == 100` is true, so the printf inside the braces will run.
    if (score == 100)
    {
        printf("Congratulations on a perfect score!\n");
    }

    // This condition `score > 100` is false, so this block is skipped.
    if (score > 100)
    {
        printf("This message will not be printed.\n");
    }
    printf("\n");

    // --- Part 2: The `if-else` Statement ---

    /*
     * The `else` statement provides an alternative block of code to execute
     * when the `if` condition is false.
     *
     * Syntax:
     * if (condition) {
     *     // Code to execute if 'condition' is true
     * } else {
     *     // Code to execute if 'condition' is false
     * }
     */
    int number_to_check = 0;

    printf("--- Part 2: The 'if-else' Statement ---\n");
    printf("Enter a whole number: ");

    /*
     * Remember the input check from Lesson 3? Now you can read it fully.
     * `scanf` returns how many items it read. The condition
     * `scanf(...) != 1` is TRUE when reading failed, so the `if` block runs
     * and the program stops before it can use a number it never received.
     */
    if (scanf("%d", &number_to_check) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    // We use the modulus operator `%` to check for an even number.
    // If a number divided by 2 has a remainder of 0, it's even.
    if (number_to_check % 2 == 0)
    {
        printf("%d is an even number.\n", number_to_check);
    }
    else
    {
        printf("%d is an odd number.\n", number_to_check);
    }
    printf("\n");

    // --- Part 3: The `if-else if-else` Chain ---

    /*
     * To check for multiple, mutually exclusive conditions, you can chain
     * `else if` statements. The program will check each condition in order.
     * As soon as it finds a true condition, it runs that block and skips the
     * rest of the entire chain. The final `else` is optional and acts as a
     * "catch-all" if none of the preceding conditions were true.
     */
    int user_grade = 0;

    printf("--- Part 3: The 'if-else if-else' Chain ---\n");
    printf("Enter your numerical grade (0-100): ");
    if (scanf("%d", &user_grade) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    if (user_grade >= 90)
    {
        printf("Your letter grade is A.\n");
    }
    else if (user_grade >= 80)
    {
        printf("Your letter grade is B.\n");
    }
    else if (user_grade >= 70)
    {
        printf("Your letter grade is C.\n");
    }
    else if (user_grade >= 60)
    {
        printf("Your letter grade is D.\n");
    }
    else
    {
        printf("Your letter grade is F.\n");
    }

    /*
     * Note on logical combinations:
     * We can use logical operators (`&&`, `||`) to create more complex conditions.
     * For example, to check if a grade is a B (80-89):
     */
    if (user_grade >= 80 && user_grade < 90)
    {
        printf("This is a solid B.\n");
    }

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you've learned how to give your program a brain.
 *
 * Key Takeaways:
 * - The `if` statement executes code only if a condition is true.
 * - The `if-else` statement provides an alternative path for when the condition is false.
 * - The `if-else if-else` chain allows you to test a series of conditions in order,
 *   executing only the first one that is true.
 * - These constructs are the fundamental building blocks for creating logic
 *   and making your programs smart and responsive.
 *
 * HOW TO COMPILE AND RUN THIS CODE:
 *
 * 1. Open a terminal or command prompt.
 * 2. Navigate to the directory where you saved this file.
 * 3. Use the GCC compiler to create an executable file:
 *    `gcc -Wall -Wextra -std=c17 -o 5_conditional_statements 5_conditional_statements.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./5_conditional_statements`
 *    - On Windows (WSL): `./5_conditional_statements`
 */

How to Compile and Run

Runs the lesson in Compiler Explorer (GCC 16.2), nothing to install.

Once, before your first lesson

Install Apple's command line tools. They include the cc compiler: xcode-select --install

New to the terminal? The setup guide walks through it.

Build

$ cc -Wall -Wextra -std=c17 -o 5_conditional_statements 5_conditional_statements.c

Run

$ ./5_conditional_statements
  • Run these commands in the folder that holds the lesson's file. Download it as a zip.
  • The program waits for your input: type an answer and press Enter.

Try It Yourself

Practise what this lesson taught. Change a copy of the lesson file, or start a new one.

  1. Read a temperature in Celsius and print "freezing", "cold", "mild" or "hot" for ranges you choose.
  2. Reject grades outside 0-100 with an error message before the grade chain runs.
  3. Read three integers and print the largest. Make sure it works when two of them are equal.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/05-conditional-statements/ in the repository and on this lesson's page on the website.

Solutions

One worked solution for each exercise above, with the reasoning in its comments. They stay closed until you open them: have a go first, then compare.

Show the solution to exercise 1
1_temperature.c 64 lines View on GitHub
/**
 * @file 1_temperature.c
 * @brief Lesson 5, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Read a temperature in Celsius and print "freezing", "cold", "mild" or "hot"
 * for ranges you choose.
 */

#include <stdio.h>

int main(void)
{
    // A temperature can have a decimal part (21.5), so it is a `double`.
    // Remember: `scanf` reads a `double` with `%lf`.
    double celsius = 0.0;

    printf("Enter a temperature in Celsius: ");
    if (scanf("%lf", &celsius) != 1)
    {
        printf("That was not a number. Exiting.\n");
        return 1;
    }

    // The ranges chosen here: below 0 is freezing, 0 up to 10 is cold,
    // 10 up to 25 is mild, and 25 or more is hot.
    //
    // The chain is checked from the top and stops at the first condition
    // that is true. So when the second test runs, we already know the
    // temperature is NOT below 0, and `celsius < 10` is enough: there is no
    // need to write `celsius >= 0 && celsius < 10`.
    if (celsius < 0)
    {
        printf("%.1f degrees is freezing.\n", celsius);
    }
    else if (celsius < 10)
    {
        printf("%.1f degrees is cold.\n", celsius);
    }
    else if (celsius < 25)
    {
        printf("%.1f degrees is mild.\n", celsius);
    }
    else
    {
        printf("%.1f degrees is hot.\n", celsius);
    }

    return 0;
}

/*
 * TEST THE EDGES
 *
 * Bugs in a chain like this hide at the boundaries, so test the values
 * where one range ends and the next begins: -0.5, 0, 9.9, 10, 24.9 and 25.
 * Decide what you want 0 and 10 to print, then check that they do.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_temperature 1_temperature.c
 *   ./1_temperature
 */
Show the solution to exercise 2
2_grade_range.c 69 lines View on GitHub
/**
 * @file 2_grade_range.c
 * @brief Lesson 5, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Reject grades outside 0-100 with an error message before the grade chain
 * runs.
 */

#include <stdio.h>

int main(void)
{
    int user_grade = 0;

    printf("Enter your numerical grade (0-100): ");
    if (scanf("%d", &user_grade) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    // Reading a number is not the same as reading a SENSIBLE number. The
    // lesson's chain would call 250 an A and -40 an F. A grade is wrong if
    // it is below 0 OR above 100, so the two tests are joined with `||`.
    //
    // Checking first and returning early keeps the chain below simple: by
    // the time it runs, the grade is known to be in range.
    if (user_grade < 0 || user_grade > 100)
    {
        printf("Error: %d is not a grade between 0 and 100.\n", user_grade);
        return 1;
    }

    if (user_grade >= 90)
    {
        printf("Your letter grade is A.\n");
    }
    else if (user_grade >= 80)
    {
        printf("Your letter grade is B.\n");
    }
    else if (user_grade >= 70)
    {
        printf("Your letter grade is C.\n");
    }
    else if (user_grade >= 60)
    {
        printf("Your letter grade is D.\n");
    }
    else
    {
        printf("Your letter grade is F.\n");
    }

    return 0;
}

/*
 * Try -1, 0, 100 and 101. The first and last must be rejected; 0 and 100
 * are real grades and must not be. `<` and `>` (rather than `<=` and `>=`)
 * are what let 0 and 100 through.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_grade_range 2_grade_range.c
 *   ./2_grade_range
 */
Show the solution to exercise 3
3_largest_of_three.c 81 lines View on GitHub
/**
 * @file 3_largest_of_three.c
 * @brief Lesson 5, Exercise 3: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Read three integers and print the largest. Make sure it works when two of
 * them are equal.
 */

#include <stdio.h>

int main(void)
{
    int first = 0;
    int second = 0;
    int third = 0;

    printf("Enter the first whole number: ");
    if (scanf("%d", &first) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    printf("Enter the second whole number: ");
    if (scanf("%d", &second) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    printf("Enter the third whole number: ");
    if (scanf("%d", &third) != 1)
    {
        printf("That was not a whole number. Exiting.\n");
        return 1;
    }

    // Keep the best candidate so far in its own variable. Start by assuming
    // the first number is the largest, then let each of the others replace
    // it if it is bigger.
    int largest = first;

    if (second > largest)
    {
        largest = second;
    }

    if (third > largest)
    {
        largest = third;
    }

    printf("The largest is %d.\n", largest);

    return 0;
}

/*
 * WHY THIS HANDLES EQUAL NUMBERS
 *
 * These are two separate `if` statements, not an `if-else` chain, because
 * both questions must always be asked. When two numbers are equal, `>` is
 * false, nothing is replaced, and `largest` already holds that value. Try
 * 5 5 3, 3 5 5, 5 3 5 and 4 4 4.
 *
 * The other common solution compares everything with everything:
 *
 *   if (first >= second && first >= third) ... else if (second >= third) ...
 *
 * It works, but only with `>=`. Written with `>`, the input 5 5 3 makes the
 * first test false (5 > 5 is false) and the program can pick the wrong
 * branch. The "best so far" pattern above has no such trap, and it is the
 * one you will reuse in Lesson 8 to find the largest value in an array.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_largest_of_three 3_largest_of_three.c
 *   ./3_largest_of_three
 */

Finished this lesson?

Mark it complete to track your progress through the course.

Search the course

Type at least two letters. Press / anywhere to search.

↑ ↓ to choose, Enter to open. On a lesson, j and k go to the next and previous lesson.