Data is useless unless you can do something with it. This lesson looks at operators which allow us to manipulate data.
There are a small number of basic operators which you must know right away. They are:
It is assumed that you know how addition, subtraction, multiplication, and division work. You probably haven't heard of modulus before. Modulus is the remainder after a division. For example, 53 / 3 is 17 with a remainder of 2, so the modulus is 2. Therefore 53 % 3 is 2.
What is 39 % 3? What is 25 % 6? The answers are 0 and 1 respectively.
If you have had basic algebra, you are probably familiar with the concept of operator precedence. All the term means is that certain operations, such as multiplication and division, will be performed before others, such as addition and subtraction. If you want to change the order, you can use parentheses.
Note: Remember that multiplication and division occur before addition and subtraction.
Examples: num = 5 + 3 * 6 /* Ans: 23 (multiply goes first) */ num = (5 + 3) * 6 /* Ans: 48 (parentheses go first) */ num = 6 / 2 * 4 /* Ans: 12 (ties are evaluated left to right) */ num = 5 % 3 /* Ans: 2 (5 / 3 leaves a remainder of 2) */
Since scanf() has already been covered, this section will be listed in a condensed format.
Example code fragment: get two numbers from user and display them.
int num1, num2; printf("Please enter an integer: "); scanf("%d", &num1); printf("Please enter another integer: "); scanf("%d", &num2); printf("You entered %d and %d\n", num1, num2);
scanf() conversion specifiers:
The assignment operator (=) is an operator with very low precedence. Everything to the right of the "=" sign is evaluated and the result is stored in the location specified by the variable name to the left of the "=" sign.
Example code fragment: Calculate the square of a number
float num1, square; printf("Enter an integer: "); scanf("%f", &num1); square = num1 * num1; printf("The square of the number you entered is %f\n", square);