We’ve learned that programming is essentially either processing data or moving them around, so we ‘operate’ on data. To do flow control, we need to construct conditions, thus we do logic operations too. In C programming, we use operators do all that.
An operator is a symbol that operates on value or variable, or on condition. For example, we already know that ‘+’ is a operator to perform addition.
C language provides a wide range of operators to support different operation needs. Let’s learn a few of the basic ones here.
Arithmetic Operators
+ | addition |
– | subtraction |
* | multiplication |
/ | division |
% | modular division |
Modular division gives us the remainder after the division, for example,
The ‘-‘ can also be used on a value or variable to negate it, for example, if x = 5, then -x equals to -5.
‘++’ and ‘–‘ are called increment and decrement operators, they can be applied to a variable. The ‘++’ is equivalent to +1, and ‘–‘ to -1. So if x = 1; then after ++x or x++, x becomes 2. You may wonder what is the difference between ‘x++’ and ‘++x’ then? We will learn it later on, but that would be something fun for a research.
When we do math, it usually takes the following form,
x = y + z;
Sometime though, we want to operate on the same variable, like the following,
For that, we can use a simpler form,
Relational Operators
These are operators we use for conditions.
== | equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
!= | not equal to |
They operate on two variables or a variable and a value, we then use the result for decision making, or flow control as we just learned. For example,
if ( a != b) { /* do something here if a is not equal to b */ }
Logical Operators
These are operators for, well, logic, as the title indicates. We use them to combine condition expressions.
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
For example,
Note that it is always a good habit to use parenthesis around the conditions that we do logic operations on, to make the logic obvious.
There are other operators, which we will learn later, for now these should be sufficient for us to do some interesting math.
Next, let’s look at how we write our code to make that interesting math more manageable …