Addition, subtraction, multiplication and division are some of the most basic tasks you will perform as a programmer. In fact, doing math is so common in programming that shortcuts have been developed to represent certain mathematical operations.
|+||addition||5 + 3|
|–||subtraction||4 – 3|
|*||multiplication||8 * 2|
|/||division||4 / 2|
Below is a simple example of how to add two integer numbers. At the end of the program, value printed out should be 8.
int i = 4; i = i + 5; print(“ i is: ” + i);
The above computation takes the current value held by the variable “i,” adds 4 to it, and then puts the new value back into “i.” At the end of the program, “i” should be 9. This type of computation is so common that a shortcut was developed to make it less cumbersome for programmers to write.
|+=||x = x + 4||x += 4|
|-=||x = x – 2||x -= 2|
|*=||x = x * 5||x *= 5|
|/=||x = x / 2||i /= 2|
int number = 6; number++; print(“number is: ” + number); </div> <div class="output"> number is 7 </div> <p><div class="note">Decrementing</div> The next program subtracts 1 from 6, and should print 5.</p> <div class="code"> int number = 6; number--; print(“number is: ” + number); </div> <div class="output"> number is 5
|++||x = x + 1||x++|
|—||x = x – 1||x–|