Comp 101 Syntax Tips and Tricks

Updating a Variable's Value

Often, we want to update the value of a variable and immediately reassign the same variable to that updated value

eg:

let heads = 1;
let tails = 2;
if (landedHeads) {
    heads = heads + 1;
} else {
    tails = tails + 1'

Is there a faster way we could do this?

There is! 

We have a variety of 'shortcuts' to allow us to reassign variables without typing the variable twice.

x = x + 7;
// becomes 
x += 7;
x = x - 7;
// becomes
x -= 7;
x = x * 7;
// becomes
x *= 7;
x = x / 7;
// becomes
x /= 7;


Adding/Subtracting 1 from a Variable

There are 3 ways we can add or subtract 1 from a variable

  • The first is just to reassign the variable in a format similar to normal addition
i = i + 1; //addition
i = i - 1; //subtraction
  • The second is using the += operator, which adds/subtracts something to/from a variable, then stores the result of the addition/subtraction in the same variable
i += 1; //addition
i -= 1; //subtraction
  • The final way to add or subtract 1 from a variable is to use the ++ or -- operators, which add or subtract 1 from a variable and store it inside the variable
i++; //adds 1 to the current value of i and stores it back into 1
i--; //subtracts 1 from the current value of i and stores it back into 1

Where could we use this?

Loops are a great place to use these shortcuts, as they usually involve incrementing a counter variable.

let i = 0;
while (i < 5) {
    if (i * 2 < 6) {
    print("Hello");
} else {
    print("World");
}
    i++;
}
What would the output of the above code be? What would i's value be each time the loop runs?