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.

Operator | Description | Example |
---|---|---|

+ | 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 numberOne = 5;
int numberTwo = 3;
int sum = numberOne + numberTwo;
print(“Sum is: ” + sum);

Assignment Operators

You can also do math as part of assigning a value to a variable. For example, if you wanted to add five to a value held by a variable, you can do the following:
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.

Operator | Same as | Example |
---|---|---|

+= | x = x + 4 | x += 4 |

-= | x = x – 2 | x -= 2 |

*= | x = x * 5 | x *= 5 |

/= | x = x / 2 | i /= 2 |

Increment and Decrement Operators:

The most common computation that programmers do is adding 1 and subtracting 1 from a value. In fact, this operation is so common that there are special operators called the increment (++) and decrement operators ( — ) to make adding 1 and subtracting 1 easier to write.
Incrementing

For example, the following program adds 1 to 6, and should print 7.
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

Operator | Same as | Example |
---|---|---|

++ | x = x + 1 | x++ |

— | x = x – 1 | x– |

## Leave a Reply