Apples and Oranges explainer


#1

Aim of the puzzle: To use the assignment operators ++ and -- to increment and decrement variables by 1.
Walk through of solution:

The first two lines of the puzzle’s starter code declare two variables: oranges and apples, and give both the value of 2.

To complete this puzzle, we need to add 1 to the oranges variable, and subtract 1 from the apples variable. Both hold the value of 2. What would happen if we just wrote oranges + 1 and apples - 1?

oranges + 1 equals 3, and apples - 1 equals 1. However, the apples and oranges variables have not been changed. Both still have the value 2. To change their values, the variables must be reassigned.

That would look like this:

oranges = oranges + 1;
apples = apples - 1;

These two lines can be replaced with two useful shortcuts, the ++ and -- assignment operators.
oranges++ is the same as writing oranges = oranges + 1, and apples-- is the same as writing apples = apples - 1.

In this puzzle, oranges++ has already been written as an example. To complete the puzzle, add the -- assignment operator to the apples variable.

Sample code solution:

let oranges = 2;
let apples = 2;
print('There are ' + oranges + ' oranges and ' + apples + ' apples.');
oranges++;
apples--;

print('There are now ' + oranges + ' oranges and ' + apples + ' apples.');

Javascript Concepts: Variable Declarations, Variable Assignments, Assignment Operators
Grasshopper Concepts: print()