An important tool when writing any computer program is making calculations. In the C programming language we use different operators to perform calculations.

A unary operator is one that acts on a single operand. This is an operation we perform on a single variable. This includes inversion, increment and decrement, etc.

int x;
int y;

x = 4;
y = !x; // This assigns y to be the inverse of x. ie. y = -4

x+=1; //This is identical to writing x = x+1 ie. x = 5  

Post Increment vs Pre Increment

int a = 3;
int b0 = 1;
int b1 = 1;

int x = a + b0++; 
int y = a + ++b1;  

Note that despite having similar syntax the post increment, a++ and pre increment ++a, they perform in different order, and should be used with caution to avoid unexpected results.
You can see that the line:

 int x = a + b0++; 

Results in x = 3 + 1 = 4, then increments b0 to be equal to 2
However the next line:

int y = a + ++b1;  

Results in x = 3 + (1+1), b1 is first incremented to 2 then added to a.

The decrement operator: —
Works in the exact same way except decrements the operand opposed to incrementing it by 1.

Binary Operators
Binary means 2. Accordingly, a binary operators is one that involves 2 operands.

Binary arithmetic operators are anything from math, this includes addition(+), subtraction(-), division(/), assignment(=), etc.

int a = 2 + 1; //assigns a to the sum of 2 and 1, ie. 3
int x = 3; //The "=" symbol is called the assignment operator
int y = x * 7; //assigns y to the product of x and 7, ie. 21

Another very useful binary arithmetic operator is called the modulus operator, %.
This operator returns the remainder of a / b.
Note that if b is greater than a: The result of a % b will be a.
This operator is very useful because of its versatility. For example, say you wish to check if a number is even,
if a number is even than the result of the following must be 0:

int x = 4;
int isEven = x % 2;

Any number mod 2 is 0 if it’s even.
Another useful feature of the modulus operator is it’s ability to dissect a number.
Say we want to write a program that accepts input from a user and prints off the last digit.
To get the last digit, we can take the number and mod it by 10.

int x;
int lastDig;

printf("Enter a digit greater than 0: ");
scanf("%d", &x);

lastDig = x % 10;

printf("The last digit of your number is: %d", lastDign");

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s