C Operators
Constants fixed values in place. An operator is a mark that tells the program to do a job on values, like + for add.
Arithmetic with five operators
a holds 10 and b holds 3. The five prints show 13, 7, 30, 3, and 1, in that order.
#include <stdio.h>
int main() {
int a = 10;
int b = 3;
printf("%d\n", a + b);
printf("%d\n", a - b);
printf("%d\n", a * b);
printf("%d\n", a / b);
printf("%d\n", a % b);
return 0;
}Shorter assignment
score starts at 10, rises to 15, then falls to 12. The two prints prove each change landed.
#include <stdio.h>
int main() {
int score = 10;
score += 5;
printf("%d\n", score);
score -= 3;
printf("%d\n", score);
return 0;
}One more and one less
count starts at 5, rises to 6, then falls back to 5. The two prints prove each step.
#include <stdio.h>
int main() {
int count = 5;
count++;
printf("%d\n", count);
count--;
printf("%d\n", count);
return 0;
}Example
#include <stdio.h>
int main() {
int total = 20;
total += 5;
total -= 2;
total *= 2;
printf("%d\n", total);
printf("%d\n", total % 7);
return 0;
}Key points
- An operator is a mark that tells the program to do a job on values, like + for add.
- + adds, - subtracts, * multiplies, and / divides.
- % gives the remainder after a division, like 10 % 3 is 1.
- Division of two ints drops the decimal part, so 10 / 3 is 3.
- = gives a value, and += adds a value to the one already there.
- score += 5 is a short form of score = score + 5.
- ++ adds one, and -- takes one away.
total starts at 20 and ends at 46, after adding 5, taking 2, and doubling. The last line prints 4, the remainder of 46 divided by 7.
Note
% works on whole numbers, and it gives the remainder, not the decimal part.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the value of 10 % 3?