Yesterday we talked about variables. Today we will talk about an arithmetic operators that can be applied to your variable.

An arithmetic operator is one that applies some type of math to a value.

Let's first look at an example of code. For instance, if you wanted to add a 1 onto an integer variable, the most basic way to do this is by doing the following:

set @integer = @integer + 1

Since you want to add 1 onto the original value of your integer, you have to set the variable equal to your current value plus 1. Using the above, however, requires unnecessary retyping. A better way to approach this would be to use the Add Equal operator, like so:

set @integer += 1

The above will add one onto the current value of the variable @integer, while only using our variable once. This gives us less of a chance of a spelling mistake. The same works for the Subtract Equals (-=), Multiply Equals (*=) and Divide Equals (/=) operators.

If we create different integer variables, we can see how each works

declare @integer1 int = 1

declare @integer2 int = 1

declare @integer3 int = 2

declare @integer4 int = 2

set @integer1 += 1

print @integer1

set @integer2 -= 1

print @integer2

set @integer3 *= 2

print @integer3

set @integer4 /= 2

print @integer4

We would get the following results:

2 (1 + 1 = 2)

0 (1 - 1 = 0)

4 (2 * 2 = 4)

1 (2 / 2 = 1)

As a programmer, it is always better not to have to retype code or variables. In this case, you are saving yourself from retyping variables.

To read more on Arithmetic Operators, go here: Arithmetic Operators

## No comments:

## Post a Comment