After studying the variables, we are now going to study the different types of operations, starting with the arithmetic operations (addition, multiplication, etc.).
First, let's clarify the vocabulary related to operators:
x = a + b;
In the example above, we add the variables a
and b
in order to put the result in x
.
a
and b
are the operands. +
.x = -a;
In the above example, we calculate the opposite of the variable a
in order to assign the result to x
.
a
is the operand. -
(or negation).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.
Write a program that declares 3 variables a
, b
and x
(type int
).
a
and b
to 5 and 78 respectivelya
by b
and puts the result in x
.x
.#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;
}
Write a program that declares 5 variables of type double
:
y
is not initializedx1
having a value of 18x2
having a value of 13x3
having a value of 5x4
having a value of 2The 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;
}
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.
In the following instruction, what are the operands?
x = a - b;
In the following statement, what are the operators ??
x = a + b*c;
What is a unary operator?
What is a binary operator?
What will the variable x
contain after the following line?
x = 2 + 3*5 - 1;