Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Arithmetic Operations

Welcome to your fifth lesson. In our previous session, we covered the essentials of storing data by declaring and initializing variables of different basic types like int, float, double, and char. This gave us the "nouns" of our C programs—the named places to hold information.

Today, we'll introduce the "verbs." Now that we can store numbers, it's time to learn how to perform calculations with them. This lesson is focused on our next learning outcome: to use arithmetic operators to perform calculations. We will explore the fundamental mathematical operators in C that allow you to add, subtract, multiply, divide, and more.

Part 1: The Five Basic Arithmetic Operators

C provides five primary arithmetic operators to handle most common calculations. Four of these will be very familiar from basic math:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)

The fifth operator might be new; it's the modulus operator:

  • % (Modulus), which gives the remainder of a division.

The following video provides an excellent, hands-on introduction to these operators, demonstrating how to use them in a complete program. Pay close attention to the distinction it makes between how division works with integers versus floating-point numbers.

Using Arithmetic Operators - C Programming Tutorial 07

Watch these sections from the video "Using Arithmetic Operators" by mycodeschool. It builds a simple calculator program from scratch.

Focus on these parts: Addition, Subtraction, Multiplication: This covers the three most straightforward operators and shows how to integrate them into a program that takes user input. Division with Integers and Floats: This is a crucial section. Note how 9 / 2 gives 4 when using int variables (integer division truncates the decimal), but gives 4.5 when using float variables. The Modulus Operator: This explains how to get the remainder of a division using %. Also, note the useful tip on how to print a literal percent sign in printf by using %%.

To summarize the key ideas from the video:

  • Integer Division: When the / operator is used with two integers, the result is also an integer. Any fractional part is discarded (truncated), not rounded. For example, 10 / 3 evaluates to 3.
  • Floating-Point Division: If at least one of the operands in a division is a floating-point number (float or double), the result will be a floating-point number. For example, 10.0 / 3 evaluates to 3.333333....
  • Modulus Operator (%): This operator gives you the remainder of an integer division. It only works with integer types. For example, 10 % 3 evaluates to 1, because 10 divided by 3 is 3 with a remainder of 1.
This diagram provides a clear visual for the modulus operator. When 13 is divided by 3, you can fit four groups of 3 into 13, with a remainder of 1. Therefore, `13 % 3` equals `1`.

Part 2: Forcing Floating-Point Division with Type Casting

In the video, you saw how using float variables produces a floating-point result. But what if your numbers are already stored in int variables and you need an accurate decimal result from a division?

You can't just assign the result to a float, because the integer division will happen first. For example:

int a = 10;
int b = 4;
float result = a / b; // result will be 2.0, not 2.5!

The expression a / b is evaluated first. Since both a and b are integers, the result is 2. Then, the integer 2 is converted to a float 2.0 and stored in result.

To fix this, you need to tell the compiler to treat one of the integers as a float before the division occurs. This is done using a type cast.

Arithmetic Operators in C

This article from Tutorialspoint clearly explains why integer division can be surprising and how to solve it with type casting.

Read the section titled Type Casting in C. It walks through the problem and demonstrates the solution by placing (float) before one of the variables in the division.

The syntax for type casting is to put the desired type in parentheses before the variable: (float)a. This creates a temporary floating-point copy of a for the calculation, forcing floating-point division.

Here's the corrected code:

int a = 10;
int b = 4;
// By casting 'a' to a float, we force floating-point division.
float result = (float)a / b; // result is now 2.5

Part 3: Order of Operations

When you combine multiple operators in a single expression, C follows a strict order of operations, just like in mathematics. This order is determined by precedence and associativity.

  • Precedence: Determines which operators are evaluated first. Multiplication, division, and modulus have a higher precedence than addition and subtraction.
  • Associativity: Determines the order for operators with the same precedence. For arithmetic operators, the associativity is left-to-right.

The next video explains these rules clearly.

Arithmetic Operators in C

The video "Arithmetic Operators in C" from Neso Academy provides a formal explanation of these rules.

Precedence and Associativity: This section lays out the hierarchy: *, /, % are evaluated before + and -. It also explains that when precedence is equal (e.g., in a - b + c), the expression is evaluated from left to right. Expression Evaluation Examples: Watch the detailed walkthrough of how expressions like a * b / c and a + b * d - c % a are evaluated step-by-step according to the rules.

Here's a quick summary of the precedence levels:

Precedence Operators Associativity
High * / % Left-to-right
Low + - Left-to-right

You can always use parentheses () to override the default precedence and force a part of an expression to be evaluated first. For example, (a + b) * c will perform the addition before the multiplication.

Part 4: Putting It All Together

Let's apply what we've learned in a practical coding exercise. The following program performs all the basic arithmetic operations on two integer variables.

Action: Create a new file named arithmetic.c, then type, compile, and run the following code.




#include <stdio.h>

int main() {
    int a = 20;
    int b = 4;

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

    // Perform and print the sum
    printf("Sum: \t\t %d + %d = %d\n", a, b, a + b);

    // Perform and print the difference
    printf("Difference: \t %d - %d = %d\n", a, b, a - b);

    // Perform and print the product
    printf("Product: \t %d * %d = %d\n", a, b, a * b);

    // Perform integer division
    printf("Integer Division: %d / %d = %d\n", a, b, a / b);

    // Perform floating-point division using a type cast
    printf("Float Division:   %d / %d = %.2f\n", a, b, (float)a / b);

    // Perform the modulus operation
    printf("Modulus: \t %d %% %d = %d\n", a, b, a % b);

    return 0;
}

Challenge:
After running the code, try to predict the output for the following line before adding it to your program. Then, add it and check your answer.
printf("Complex expression: %d\n", (a + 5) * 2 - b / 2);

Food for thought:
The modulus operator is surprisingly useful. How could you use the expression number % 2 to determine if an integer is even or odd? (Hint: what is the remainder when an even number is divided by 2? What about an odd number?)

Conclusion

In this lesson, you've added the fundamental tools for performing calculations to your C programming toolkit. You can now not only store data but also manipulate it to produce new results.

Here are the key takeaways:

  • C has five main arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), and % (modulus).
  • Integer division (/) with two integers truncates the result, discarding any remainder.
  • To get a precise decimal result from division, at least one operand must be a float or double. You can use a type cast like (float) to temporarily treat an integer as a float for a calculation.
  • The modulus operator (%) gives the remainder of an integer division and is very useful for tasks like checking for divisibility.
  • Expressions are evaluated according to operator precedence (* / % before + -) and left-to-right associativity. Parentheses () can be used to control the order.

So far, we've been assigning values to our variables directly in the code. This is great for learning, but real programs need to interact with the user. In our next lesson, we will learn how to read input directly from the user's keyboard using the scanf function.

Can't find a good explanation? Sign up and we'll make it for you

Sign up