Mathematical operators can be used for calculation purposes and logical purposes.
Mathematical Operators
These operators compute different types of calculation based on the operators.
These are the basic mathematical operators:
+ (used for addition)
- (used for subtraction)
* (used for multiplication)
/ (used for division)
% is the modulus/modulo operator. This is used to get the remainder of a calculation
Unary expressions
Unary expressions consist of 1 operator and 1 operand. Operands are the numbers or the variables or both.
Example of unary expressions are:
-5, +5.
Binary expressions
Binary expressions consits of 2 operands and 1 operator and commonly seen then the following form:
[operand][operator][operand]
Example:
5 + 2
8*a
a/b
To store a computed value from a binary expression into a variable, the assignment operator is used, denoted as =.This is different from mathematics where = is equal but almost similar.
a= a+1 is not valid in mathematics because a does not equal a+1. In C language or most languages, a = a+1 is perfectly fine as this tells that the value of a plus 1 is then stored into the variable a.
Examples:
a= b*c;
b=(5*2)+c;
NOTE: The assignment operator can only be used to assign values to a variable, where the left hand side is always the variable. Any other expressions such as:
b+c = a
2+3 = a
are invalid in programming languages.
There are 3 forms of assignments: simple assignments, compound assignments and multiple assignments.
- Simple Assignments
b= 4+a;
a= a*b;
- Similarly, some simple assignments can be re-written in another form called compound assignments.
a=a*b can be rewritten to a *= b
a = a/b can be rewritten to a /=b
a = a+b can be rewritten to a +=b
a = a -b can be rewritten to a -=b
a = a%b can be rewritten to a %=b
Therefore, we can conclude that compound assignments can be used when the first operand is the same as the variable is assigned to it.
- Multiple assignments
a = b = 1+2
The expression above can be separated as below:
b= 1+2
a=b
This tells us that the value of 1+2 is stored/assigned into b and the value of b is assigned to variable a.
And another note, all expressions and statements are to end with a terminated colon unless specified otherwise.
No comments:
Post a Comment