Lesson 3.1. Arithmetic operators

After studying the variables, we are now going to study the different types of operations, starting with the arithmetic operations (addition, multiplication, etc.).

Vocabulary

First, let's clarify the vocabulary related to operators:

Example of operator and operands in a C instruction

Example 1

x = a + b;

In the example above, we add the variables a and b in order to put the result in x.

Example 2

x = -a;

In the above example, we calculate the opposite of the variable a in order to assign the result to x.

Arithmetic operators

In C, there are 5 arithmetic operators:

Operator Symbol Type
Addition + unary or binary
Subtraction - unary or binary
Multiplication * binary
Division / binary
Modulo % binary

Note: The operators power, square root, exponential, sine, etc. are not native C operators. they have been implemented in the math.h library .

We will explain the modulo in the next lesson.

Exercise 1

Write a program that declares 3 variables a, b and x (type int).

#include <stdio.h>

int main(void) {
    // Declare x, a=5 et b=78 (type int)
    // COMPLETE HERE

    // Multiply a by b => x
    // COMPLETE HERE

    // Display x
    printf ("x = %d\n", x);

    return 0;
}

Exercise 2

Write a program that declares 5 variables of type double :

The program performs and displays the result of the following calculation:

$$ y = \dfrac {x1+x2} {x3-x4} $$

#include <stdio.h>

int main(void) {
    // Declare the variables y, x1, x2, x3 et x4
    // COMPLETE HERE

    // Calculation
    // COMPLETER ICI

    // Display the result
    printf ("y = %lf\n", y);

    return 0;
}

Exercise 3

Write a program that converts the angle alpha from degrees to radians (see formula).

// Angle to convert 
double alpha = 90;

// Convert angle from degrees to radians
// COMPLETE HERE

// Displays the converted angle
printf ("alpha = %lf rad.\n", alpha);

For the value of π, you can use the constant M_PI declared in the math.h library.

Quiz

In the following instruction, what are the operands?

x = a - b;
Check Bravo! Operands are the elements on which an operation is applied. Try again...

In the following statement, what are the operators ??

x = a + b*c;
Check Bravo! There are two operators: multiplication and addition. Try again...

What is a unary operator?

Check Bravo! A unary operator accepts only one operand. Try again...

What is a binary operator?

Check Bravo! A binary operator applies to two operands. Try again...

What will the variable x contain after the following line?

x = 2 + 3*5 - 1;
Check Bravo! Multiplication is a priority. Try again...

See also


Last update : 11/21/2022