Skip to content

Part 1 · Lesson 4

Basic Operators

On this page

What you'll learn: arithmetic, relational and logical operators, integer division, the modulus operator and operator precedence.

Before you start: Lessons 1-3.

In programming, an OPERATOR is a special symbol that performs an operation on one or more values or variables (called OPERANDS). For example, in 5 + 3, the + is the operator and 5 and 3 are the operands.

We will explore three main categories of operators in this lesson:

  1. Arithmetic Operators: For performing mathematical calculations.
  2. Relational Operators: For comparing two values.
  3. Logical Operators: For combining multiple comparisons.

Arithmetic Operators

The lesson works with two integers:

int a = 10;
int b = 3;

+ (addition), - (subtraction) and * (multiplication) work just as they do in math: a + b is 13, a - b is 7 and a * b is 30.

/ (Division)

This one is tricky! When you divide two integers in C, the result is also an integer. The fractional part is simply thrown away (truncated). This is called INTEGER DIVISION. So a / b is 3, not 3.333.

To get a precise decimal result, at least one of the operands must be a floating-point type (like double). We can achieve this by "casting" one of the integers to a double:

double precise_division = (double)a / b;

Now precise_division holds 3.333333.

% (Modulus)

This operator gives you the REMAINDER of an integer division. a % b is 1, because 10 divided by 3 is 3 with 1 left over. It is incredibly useful: for example, n % 2 is 0 exactly when n is even. (To print a % sign with printf, write %%, because a single % starts a format specifier.)

Relational Operators

RELATIONAL OPERATORS are used to compare two values. The result of a relational operation is a "truth" value, and in C that value is an int:

  • 0 represents FALSE.
  • Any non-zero integer represents TRUE. Comparisons always give 1.

The six relational operators are == (equal to; note the TWO equals signs), != (not equal to), >, <, >= and <=. With a as 10 and b as 3, a == 10 is 1 and a == b is 0.

(Modern C does have a boolean type, bool, with the values true and false. You will meet it in a later lesson. Even so, comparisons and logical operators still produce the int values 1 and 0.)

Logical Operators

LOGICAL OPERATORS are used to combine or modify logical (true/false) expressions:

  • && (AND) is true only if BOTH sides are true.
  • || (OR) is true if AT LEAST ONE side is true.
  • ! (NOT) flips a value: !0 is 1, and !1 is 0.
int is_player_alive = 1; // 1 for true
int has_key = 0;         // 0 for false

Here is_player_alive && has_key is 0 (the player cannot open the door), is_player_alive || has_key is 1, and !has_key is 1.

Operator Precedence

Just like in math (PEMDAS/BODMAS), operators in C have a default order of evaluation called OPERATOR PRECEDENCE. For example, * and / are evaluated before + and -, so 5 + 2 * 10 is 25, not 70.

You can use parentheses () to force a specific order of evaluation, just like in math: (5 + 2) * 10 is 70. It's often a good idea to use parentheses to make your code clearer, even when not strictly necessary.

Full Source

4_basic_operators.c 173 lines Download View on GitHub
/**
 * @file 4_basic_operators.c
 * @brief Part 1, Lesson 4: Basic Operators
 * @author dunamismax
 * @date 06-15-2025
 *
 * This lesson covers the fundamental operators in C used for performing
 * calculations and making comparisons.
 */

/*
 * =====================================================================================
 * |                                   - LESSON START -                                  |
 * =====================================================================================
 *
 * In programming, an OPERATOR is a special symbol that performs an operation on
 * one or more values or variables (called OPERANDS). For example, in `5 + 3`,
 * the `+` is the operator and `5` and `3` are the operands.
 *
 * We will explore three main categories of operators in this lesson:
 * 1. Arithmetic Operators: For performing mathematical calculations.
 * 2. Relational Operators: For comparing two values.
 * 3. Logical Operators: For combining multiple comparisons.
 */

#include <stdio.h>

int main(void)
{
    // Let's declare some variables to work with.
    int a = 10;
    int b = 3;

    // --- Part 1: Arithmetic Operators ---

    printf("--- Part 1: Arithmetic Operators ---\n");
    printf("Initial values: a = %d, b = %d\n\n", a, b);

    // `+` (Addition)
    printf("a + b = %d\n", a + b);

    // `-` (Subtraction)
    printf("a - b = %d\n", a - b);

    // `*` (Multiplication)
    printf("a * b = %d\n", a * b);

    /*
     * `/` (Division) - This one is tricky!
     * When you divide two integers in C, the result is also an integer.
     * The fractional part is simply thrown away (truncated). This is called
     * INTEGER DIVISION.
     */
    printf("Integer Division (a / b) = %d\n", a / b); // 10 / 3 is 3, not 3.333

    /*
     * To get a precise decimal result, at least one of the operands must be a
     * floating-point type (like `double`). We can achieve this by "casting"
     * one of the integers to a double.
     */
    double precise_division = (double)a / b;
    printf("Floating-Point Division ((double)a / b) = %f\n", precise_division);

    /*
     * `%` (Modulus)
     * This operator gives you the REMAINDER of an integer division. It is
     * incredibly useful in many programming scenarios.
     */
    printf("Modulus (a %% b) = %d\n", a % b); // 10 divided by 3 is 3 with a remainder of 1.
    // Note: To print a literal '%' character in printf, you must type '%%'.
    printf("\n");

    // --- Part 2: Relational Operators ---

    /*
     * RELATIONAL OPERATORS are used to compare two values. The result of a
     * relational operation is a "truth" value, and in C that value is an `int`:
     * - `0` represents FALSE.
     * - Any non-zero integer represents TRUE. Comparisons always give `1`.
     *
     * (Modern C does have a boolean type, `bool`, with the values `true` and
     * `false`. You will meet it in a later lesson. Even so, comparisons and
     * logical operators still produce the `int` values 1 and 0.)
     */
    printf("--- Part 2: Relational Operators ---\n");
    printf("The results below will be 1 for TRUE and 0 for FALSE.\n\n");

    // `==` (Equal to) - VERY IMPORTANT:
    // A single `=` is for assignment. A double `==` is for comparison.
    // This is one of the most common beginner mistakes!
    printf("Is a == 10? %d\n", a == 10); // True (1)
    printf("Is a == b?  %d\n", a == b);  // False (0)

    // `!=` (Not equal to)
    printf("Is a != b?  %d\n", a != b); // True (1)

    // `>` (Greater than)
    printf("Is a > b?   %d\n", a > b); // True (1)

    // `<` (Less than)
    printf("Is a < b?   %d\n", a < b); // False (0)

    // `>=` (Greater than or equal to)
    printf("Is a >= 10? %d\n", a >= 10); // True (1)

    // `<=` (Less than or equal to)
    printf("Is b <= 3?  %d\n", b <= 3); // True (1)
    printf("\n");

    // --- Part 3: Logical Operators ---

    /*
     * LOGICAL OPERATORS are used to combine or modify logical (true/false) expressions.
     */
    printf("--- Part 3: Logical Operators ---\n");
    int is_player_alive = 1; // 1 for true
    int has_key = 0;         // 0 for false
    printf("Player is alive: %d, Player has key: %d\n\n", is_player_alive, has_key);

    // `&&` (Logical AND) - evaluates to true ONLY if BOTH operands are true.
    printf("Can open door (is_player_alive && has_key)? %d\n", is_player_alive && has_key);

    // `||` (Logical OR) - evaluates to true if AT LEAST ONE operand is true.
    printf("Is player alive OR has key? %d\n", is_player_alive || has_key);

    // `!` (Logical NOT) - inverts the truth value of its operand.
    printf("The opposite of has_key (!has_key) is: %d\n", !has_key);
    printf("\n");

    // --- Part 4: Operator Precedence ---
    printf("--- Part 4: Operator Precedence ---\n");
    /*
     * Just like in math (PEMDAS/BODMAS), operators in C have a default order
     * of evaluation called OPERATOR PRECEDENCE. For example, `*` and `/` are
     * evaluated before `+` and `-`.
     */
    int result1 = 5 + 2 * 10;             // 2*10 is done first, then 5 is added.
    printf("5 + 2 * 10 = %d\n", result1); // Prints 25, not 70.

    /*
     * You can use parentheses `()` to force a specific order of evaluation,
     * just like in math. It's often a good idea to use parentheses to make
     * your code clearer, even when not strictly necessary.
     */
    int result2 = (5 + 2) * 10;             // (5+2) is done first.
    printf("(5 + 2) * 10 = %d\n", result2); // Prints 70.

    return 0;
}

/*
 * =====================================================================================
 * |                                    - LESSON END -                                   |
 * =====================================================================================
 *
 * In this lesson, you learned about C's fundamental operators:
 * - Arithmetic (`+`, `-`, `*`, `/`, `%`) for calculations.
 * - Relational (`==`, `!=`, `>`, `<`, `>=`, `<=`) for comparisons.
 * - Logical (`&&`, `||`, `!`) for combining true/false conditions.
 *
 * You also learned about integer division, the modulus operator, and how to
 * use parentheses `()` to control the order of operations.
 *
 * 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 4_basic_operators 4_basic_operators.c`
 * 4. Run the executable:
 *    - On Linux/macOS:   `./4_basic_operators`
 *    - On Windows (WSL): `./4_basic_operators`
 */

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 4_basic_operators 4_basic_operators.c

Run

$ ./4_basic_operators

Try It Yourself

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

  1. Read two integers with scanf and print their sum, difference, product, integer quotient and remainder.
  2. Print 7 / 2, 7.0 / 2 and (double)7 / 2. Explain each result.
  3. Write an expression that is 1 when an integer year is a leap year (divisible by 4, and not by 100 unless also by 400), and test it on 1900, 2000 and 2024.

Try each one yourself before you look at a worked solution. The solutions, with the reasoning in their comments, are in exercises/04-basic-operators/ 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_five_results.c 64 lines View on GitHub
/**
 * @file 1_five_results.c
 * @brief Lesson 4, Exercise 1: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Read two integers with `scanf` and print their sum, difference, product,
 * integer quotient and remainder.
 */

#include <stdio.h>

int main(void)
{
    int a = 0;
    int b = 0;

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

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

    printf("%d + %d = %d\n", a, b, a + b);
    printf("%d - %d = %d\n", a, b, a - b);
    printf("%d * %d = %d\n", a, b, a * b);

    // Dividing an integer by zero is an error the language does not define:
    // on most computers the program simply crashes. `/` and `%` both divide,
    // so both need this check. It has the same shape as the `scanf` check
    // above: "if this is true, explain and stop". Lesson 5 covers `if`.
    if (b == 0)
    {
        printf("Cannot divide by zero, so there is no quotient or remainder.\n");
        return 1;
    }

    printf("%d / %d = %d\n", a, b, a / b);
    printf("%d %% %d = %d\n", a, b, a % b);

    return 0;
}

/*
 * THINGS TO TRY
 *
 * - 17 and 5: the quotient is 3 and the remainder is 2, because
 *   17 = 3 * 5 + 2. The quotient and remainder always fit together this way.
 * - 5 and 17: the quotient is 0 and the remainder is 5.
 * - 7 and 0: the program explains instead of crashing.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 1_five_results 1_five_results.c
 *   ./1_five_results
 */
Show the solution to exercise 2
2_three_divisions.c 55 lines View on GitHub
/**
 * @file 2_three_divisions.c
 * @brief Lesson 4, Exercise 2: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Print `7 / 2`, `7.0 / 2` and `(double)7 / 2`. Explain each result.
 */

#include <stdio.h>

int main(void)
{
    // Both operands are integers, so this is INTEGER DIVISION. The exact
    // answer, 3.5, loses its fractional part and becomes 3. The result is
    // an `int`, so it is printed with `%d`.
    printf("7 / 2         = %d\n", 7 / 2);

    // `7.0` is written with a decimal point, which makes it a `double`.
    // When one operand is a `double`, C converts the other one too and
    // divides them as floating-point numbers: 3.5. The result is a
    // `double`, so it is printed with `%f`.
    printf("7.0 / 2       = %f\n", 7.0 / 2);

    // `(double)7` is a CAST: it converts the integer 7 to the `double` 7.0
    // before the division happens. From there it is the same as the line
    // above.
    printf("(double)7 / 2 = %f\n", (double)7 / 2);

    return 0;
}

/*
 * THE RULE
 *
 * The TYPES of the two operands decide which division you get, not the
 * variable the result is stored in and not the format specifier you print
 * it with. Two integers divide as integers. If either one is a `double`,
 * the division is done in floating point.
 *
 * With literal numbers you can simply write `7.0`. The cast matters when the
 * numbers are in `int` variables, as with `(double)a / b` in the lesson.
 *
 * ONE TRAP
 *
 * A cast applies to the value right after it, so `(double)7 / 2` converts
 * the 7 and then divides. Write `(double)(7 / 2)` instead and the
 * parentheses make the integer division happen first: 7 / 2 is 3, and only
 * then is that 3 converted, giving 3.0. The fraction was already gone.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 2_three_divisions 2_three_divisions.c
 *   ./2_three_divisions
 */
Show the solution to exercise 3
3_leap_year.c 61 lines View on GitHub
/**
 * @file 3_leap_year.c
 * @brief Lesson 4, Exercise 3: one possible solution
 * @author dunamismax
 * @date 11-20-2026
 *
 * THE EXERCISE:
 * Write an expression that is 1 when an integer `year` is a leap year
 * (divisible by 4, and not by 100 unless also by 400), and test it on 1900,
 * 2000 and 2024.
 */

#include <stdio.h>

int main(void)
{
    /*
     * "Divisible by 4" means the remainder of dividing by 4 is zero, which
     * is what the modulus operator tests: `year % 4 == 0`.
     *
     * The rule in words has two ways to be a leap year:
     *   1. divisible by 4 AND NOT divisible by 100, OR
     *   2. divisible by 400.
     *
     * AND is `&&` and OR is `||`. The parentheses show which parts belong
     * together. (`&&` is evaluated before `||` anyway, but the parentheses
     * make the meaning obvious to a reader, as the lesson recommends.)
     */
    int year = 1900;
    int is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    printf("Is %d a leap year? %d\n", year, is_leap); // 0

    // The expression has to be written out again for each year: a variable
    // remembers the RESULT, not the calculation. Lesson 7 shows how to give
    // a calculation a name, so you write it once and use it many times.
    year = 2000;
    is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    printf("Is %d a leap year? %d\n", year, is_leap); // 1

    year = 2024;
    is_leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    printf("Is %d a leap year? %d\n", year, is_leap); // 1

    return 0;
}

/*
 * WHY THESE THREE YEARS
 *
 * Each one tests a different part of the rule:
 * - 1900 is divisible by 4 and by 100 but not by 400: not a leap year. An
 *   expression that only checks `year % 4 == 0` gets this one wrong.
 * - 2000 is divisible by 400: a leap year, through the second way.
 * - 2024 is divisible by 4 and not by 100: a leap year, through the first.
 *
 * Add a fourth test of your own, such as 2023, which should give 0.
 *
 * HOW TO COMPILE AND RUN:
 *   gcc -Wall -Wextra -std=c17 -o 3_leap_year 3_leap_year.c
 *   ./3_leap_year
 */

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.