How to Save Time with C Programming’s Math Assignment Operators - dummies

How to Save Time with C Programming’s Math Assignment Operators

By Dan Gookin

If you’re a fan of the ++ and – operators in C programming, you’ll enjoy the operators listed below. They’re the math assignment operators, and like the increment and decrement operators, not only do they do something useful, but they also look really cool and confusing in your code.

Operator Function Shortcut for Example
+= Addition x=x+n x+=n
-= Subtraction x=x-n x-=n
*= Multiplication x=x*n x*=n
/= Division x=x/n x/=n
%= Modulo x=x%n x%=n

Math assignment operators do nothing new, but they work in a special way. Quite often in C, you need to modify a variable’s value. For example:


This statement increases the value of variable alpha by 10. In C, you can write the same statement by using an assignment operator as follows:


Both versions of this statement accomplish the same thing, but the second example is more punchy and cryptic, which seems to delight most C programmers.


#include <stdio.h>
int main()
 float alpha;
 printf("alpha = %.1fn",alpha);
 printf("alpha = %.1fn",alpha);
 printf("alpha = %.1fn",alpha);
 printf("alpha = %.1fn",alpha);
 printf("alpha = %.1fn",alpha);

Exercise 1: Type the source code from Assignment Operator Heaven into your text editor. Change Lines 9, 11, 13, and 15 so that assignment operators are used. Build and run.

When you use the assignment operator, keep in mind that the = character comes last. You can easily remember this tip by swapping the operators; for example:


This statement assigns the value -10 to the variable alpha. But the statement


decreases the value of alpha by 10.

Exercise 2: Write a program that outputs the numbers from 5 through 100 in increments of 5.