Incrementing and Decrementing Variables with Young Coders - dummies

Incrementing and Decrementing Variables with Young Coders

By Camille McCue, Sarah Guthals

Your young coder can write code that changes the value of a variable under certain conditions as the program executes. A common way to change a variable value is to increment it. To increment a variable means to increase it by the same amount at each change. For example, your coder may increment a scoring variable by +2 each time a basketball goal is made. Decreasing a variable in this way is known as decrementing the variable value. Your coder may decrement a timer by –1 each time one second on the clock elapses.

Using pseudocode

The general format for incrementing or decrementing a variable value is as follows:

Action Pseudocode Examples
Increment a variable variable = variable + change score = score + 1

numTwins = numTwins + 2

Decrement a variable variable = variable - change timeRemaining = timeRemaining - 1

cost = cost - 5

Boolean variables aren’t incremented nor decremented. A Boolean variable exists only in one of two states: true or false.

Using Scratch

To increment or decrement a variable in Scratch, follow these steps:

  1. Go to the Data blocks code tile category.
  2. Select the change variable name by value code tile and drag it into your program.
  3. Press the tab beside the variable name and select the variable whose value you want to change.
  4. Type a number for the increment or decrement in the value field. Use a positive number to increment the value. Use a negative number to decrement the value.
variable value coding
Changing a variable value in Scratch.

Using Python

To increment a variable value in Python, type the code

variableName = variableName + value

at the location in your code where you want to change the value.

To decrement a variable value Python, type the code

variableName = variableName – value

at the location in your code where you want to change the value.

Using JavaScript

To increment a variable value in JavaScript, type the code

variableName = variableName + value;

at the location in your code where you want to change the value.

To decrement a variable value in JavaScript, type the code

variableName = variableName – value;

Using Java

To increment a variable value in a Java program, type the code

variableName = variableName + value;

at the location in your code where you want to change the value.

To decrement a variable value in a Java program, type the code

variableName = variableName – value;