In this exercise, let’s consider how we can use variables and math operators to calculate new values and assign them to a variable. Check out the example below:
let x = 4; x = x + 1;
In the example above, line 1) we created the variable x with the number 4 assigned to it. On the following line 2), x = x + 1; increases the value of x from 4 to 5.
Notice, on line two in the example above, to increment x by one we had to write the x variable on the left and right side of the assignment operator (=). Using a variable twice in one expression is redundant and confusing.
let x = 4; x += 2; // x equals 6 let y = 4; y -= 2; // y equals 2 let z = 4; z *= 2; // z equals 8 let r = 4; r++; // r equals 5 let t = 4; t--; // t equals 3
In the example above, operators are used to calculate a new value and assign it to the same variable. Let’s consider the first three and last two operators separately:
1) The first three operators (+=, -=, and *=) perform the mathematical operation of the first operator (+, –, or *) using the number on the right, then assign the new value to the variable.
2) The last two operators are the increment (++) and decrement (—) operators. These operators are responsible for increasing and decreasing a number variable by one, respectively.
Exercise: Using what we have learned above complete the following:
let molecule = 16; let particle = 18; let assay = 3; // Add and assign to molecule below // Multiply and assign to particle below // Increment assay by 1
Use a mathematical assignment operator to add 16 to the value saved to molecule.
Use a mathematical assignment operator to assign particle the value of itself multiplied by 6.02.
Use the increment operator to increase the value saved to assay by 1.
4. Give up? See the answer code below.
ANSWER CODE: Here is the answer code for the exercise above.
let molecule = 16; let particle = 18; let assay = 3; // Add and assign to molecule below molecule += 16; // Multiply and assign to particle below particle *= 6.02; // Increment assay by 1 assay++;
My little pony learning game in VB.NET
Learn Partial functions Python programming
Hello World Android app built with Android Studio
Who is this Android App Development course for?
How to make a go-back button with PHP code?