In our last article we left off discussing user input and variables in C. In this episode we will cover some of the operators available to you and how to manipulate data with them.
Contributed by James Payne Rating: / 28 February 11, 2008
You have been using most of the mathematical operators available in C since you began school. They consist of the +,-,*,/,and %. Below is a table describing the function of each one:
Operator
What it Does
Example
+
Used for addition/Unary Plus
1+2 = 3
-
Used for subtraction/Unary Minus
2-1 = 1
*
Used for Multiplication
2*2 = 4
/
Used for Division
4/4 = 0
%
Used for Modulus (Returns the remainder from a division)
4%3= -1
Here is how you would use them in code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number1, number2, add, subtract, mul, div, mod;
printf("Enter two numbers separated by a space: ");
printf("n number1 divided by number2 equals %d", div);
mod = number1%number2;
printf("n The remainder of number1 divided by number2 is %d", mod);
}
In the above code you will notice a new include, the #include <stdlib.h>. We insert this when we are doing math.
The program works by creating two variables (number1 and number2) to hold the values a user will input, and then creates the add, subtract, mul, div, and mod variables to hold the results of our mathematical operations.
The program asks the user to enter two numbers, separated by a space. It then uses the scanf_s to retrieve the key strokes and store the numbers in number1 and number2 respectively. It then takes the two numbers and adds them, storing the result in the variable “add.” Then it prints out some text and the value that resides in “add.” It continues doing this for the rest of the examples. Let's say the user had input 5. The result would be:
Enter two numbers separated by a space: 5 3
number1 + number2 equals 8
number1-number2 equals 2
number1 times number2 equals 15
number1 divided by number2 equals 1
The remainder of number1 divided by number2 is -2
If we wanted to work with floating points we could do the following:
##include <stdio.h>
#include <stdlib.h>
int main()
{
float example;
float nonfloat;
float add;
printf("Please enter a decimal number and a non-decimal number: ");
scanf_s("%f %f", &example, &nonfloat);
add=example+nonfloat;
printf("n %.2f plus %.2f equals %.2f", example, nonfloat, add);
}
This program creates three variables. It then asks the user to enter a decimal number and a non-decimal number separated by a space. When the user enters the information, the first number is stored in the “example” variable and the second number is stored in the “nonfloat” variable. A calculation is then performed on both of these values and stored in the variable “add.” Finally, we print some text and append the result at the end of it. If the user has entered 1.2 and 3 as their text, then we would get the following result:
1.20 plus 3.00 equals 4.20
You will notice that we used %.2f for our placeholders. This formats the floating points to have 2 decimal places. If we had done %.3f, it would have shown three decimal places and so forth.
We can also work with what is called mixed mode arithmetic, such as 12.9 + 2. In the below example, we are going to multiply a float by a character...I know...your head's gonna explode when you see it in action. So get some Windex and paper towels...
#include <stdio.h>
#include <stdlib.h>
int main()
{
float myIQ;
char yourIQ[4];
printf("Enter your IQ: ");
gets_s(yourIQ);
myIQ = atoi(yourIQ)*5.52;
printf("My IQ is %.1f... I laugh at your puny IQ!n",myIQ);
return(0);
}
This program does several things: first, it demonstrates how superior my intelligence quotient is to yours. Second, it creates two variables, one a float and the other a character. It then gets input from the user and stores it in the variable “yourIQ.” Next, it extracts the data from yourIQ, and since it is a character variable, it translates the value into an integer using the ATOI function. Then it multiplies this new integer by 5.52 and stores its value in the variable myIQ. Finally it prints out some text and appends the value of myIQ to the end of the sentence.
If the user had lied and typed that their IQ was 129, then the result would be:
Enter your IQ: 129
MY IQ is 712.1... I laugh at your puny IQ!
You will note two new functions here:
ATOI, which I already introduced you to, but just as a reminder, it translates a value into an integer.
Gets_s, which is similar to scanf_s, except gets_s() reads only text.
When you wish to compare operands, you use relational operators. While I am going to touch on these briefly here, I will go more in depth with them when we cover statements, such as If, While, and For.
Here is a pretty table showing some of the relational operators:
Operator
What it Does
Example
<
Less than
1 < 2
>
Greater than
2 > 1
<=
Less than or equal to
1 <=1
>=
Greater than or equal to
3 >= 2
“==” (note: the quotations are added here for display purposes only; you do not include them in the operator)
Equal to
1 == 1
!=
Not equal to
1 != 2
Logical Operators
As with relational operators, we will cover logical operators more in depth when we look at statements. For now, satisfy your curiosity with this brilliant table showcasing some of them:
Operator
What it Does
Example
&&
Logical AND tests 2 conditions to see if they are true
5 > 4 && 5 < 6
||
Logical OR checks to see if any one of two expressions is true
b <c || b <d
!
Logical NOT evaluates to true if the expression is false and false if the expression is true
! 2 > 3 (result would be true, as 2 is not greater than 3)
We've been working with an assignment operator for a while now, namely the “=” operator. An example would be assigning a value to a variable: int yourWeight = 400. We can also do this: a = a+1. This will add one to the value of a. Let's say we have two variables, a and b. Variable a will hold the value of ten, and variable b will hold the value of 5. If we write a= a+b, the new value of a is 15. We can also do this using shorthand methods, like the examples below. For instance, if we typed a+=b, we would still get the result of 15, without having to write a little extra code.
Here is a table of examples of shorthand operators:
Simple Assignments
Shorthand Assignments
a=a +2
a+=2
a=a-1
a-=1
a=a*(9+2)
a*=(9+2)
a=a/(9+2)
a=/(9+2)
a=a % 9
a %= 9
Here is some code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int myIQ = 150;
int yourIQ = 12;
printf("My IQ is %i... I laugh at your puny IQ!n",myIQ);
myIQ+=yourIQ;
printf("Our combined IQ is %i...",myIQ);
return(0);
}
This code results in:
My IQ is 150...I laugh at your puny IQ!
Our combined IQ is 162...
Incremental/Decremental Operators
Used in For and While Loops, the incremental/decremental operators add or subtract the value of a variable by 1, respectively. Depending upon where you place the operator, the value will either be incremented/decremented after or before the statement is evaluated. This might not make sense at the moment, but it will soon.
Consider this statement:
mysalary = 40000;
salaryafterraise = ++mysalary;
This is known as a prefix. In the above example, the value of both mysalary and salaryafterraise would be 40001. This is because the program adds 1 to the variable mysalary PRIOR to adding mysalary to salaryafterriase.
If I had written:
mysalary = 40000;
salaryafterraise = mysalary++;
Then the value of salaryafterraise would be 40000 and the value of mysalary would be 40001. This is because when we add the incrementer post fix, it adds mysalary to salaryafterraise, then increases the value of mysalary by one.
Well that's it for this episode. We still have some more operators to cover, and we will do so in the next article, alongside the array and commenting in C. So come back often.