In many programs, you will need to do simple mathematical operations, like adding and multiplying. The C language provides the four standard operators for this, as described in the table below. There is also a fifth modulo operator, and the = operator is used for assigning values.
Operator |
Operation |
Comment |
+ |
addition |
|
- |
subtraction |
|
* |
multiplication |
|
/ |
division |
Note that if you are dividing two integers, the result will be an integer (even if the real result is fractional). |
% |
modulo |
The modulus is the amount left after an integer division. For example, 3%3 = 0, 4%3 = 1 and 5%3 = 2. |
= |
assignment |
Assigns the results of a mathematical operation to a variable. e.g.: a = 2 + 3; |
Math operators can work on either numbers or variables. There are some examples below
#include <stdio.h> int main(int argc, char* argv[]) { int a, b, c; float x, y, z; a = 8 + 12; /*value of a is 20*/ b = a - 3; /*value of b is 17*/ c = 3 / 2; /*c = 1 because c is an integer and the operation was integer division*/ x = 3 / 2; /*x = 1 Since both numbers in the division were integers, the result is an integer*/ y = 3.0 / 2; /*y = 1.5 The one number in the division was a real number, so the result will be real*/ z = x * y; /*z = 1.5*/ return 0; }More advanced mathematical operations such as exponents and sine functions are handled by using functions defined in the math library.
We will now look at controlling program flow with if statements.