Programming instructions
Reference
Project Lead The Way
©
and Carnegie Mellon Robotics Academy
©
/ For use with VEX
®
Robotics Systems
Variables • 3
Assignment and Usage Rules
Assignment of values to variables is pretty straightforward, as is the use of a variable in a
command where you wish its value to be used.
Rules for Variable Usage
• “Use” a variable simply by putting its name where you want its value to be used
• The current value of the variable will be used every time the variable appears
Examples:
Statement Description
motorPower = 75;
Stores the value 75 in the variable
“motorPower”
sonarVariable = SensorValue(sonarSensor);
Stores the current sensor reading
of the sensor “sonarSensor” in the
variable “sonarVariable”
sum = variable1 + variable2;
Adds the value in “variable1”
to the value in “variable2”, and
stores the result in the variable
“sum”
average = (variable1 + variable2)/2;
Adds the value in “variable1”
and the value in “variable2”,
then divides the result by 2, and
stores the nal resulting value in
“average”
count = count + 1;
Adds 1 to the current value of
“count” and places the result back
into “count” (effectively, increases
the value in “count” by 1)
int zero = 0;
Creates the variable x with an
initial value of 0 (combination
declaration and assignment
statement)
Rules for Assignment
• Values are assigned using the assignment operator = (not ==)
• Assigning a value to a variable that already has a value in it will overwrite the old value
with the new one
• Math operators (+, -, *, /) can be used with assignment statements to perform calculations
on the values before storing them
• A variable can appear in both the left and right hand sides of an assignment statement;
this simply means that its current value will be used in calculating the new value
• Assignment can be done in the same line that a variable is declared
(e.g. int x = 0; will both create the variable x and put an initial value of 0 in it)
Variables
Go to Reference Links