Recap of Variables I
What We’ve Covered So Far
Declaring a variable:
1 |
int distance; // an empty variable named distance for use later |
Declaring and assigning a variable at the same time:
1 |
int distance = 10; // a variable named distance with a value of ten |
Changing a variable:
1 |
distance = 15; // the distance variable changed from what it was to fifteen |
Adding to a variable:
1 2 3 |
distance = distance + 15; //or below does the same thing, just in shorthand distance += 15; |
Adding and subtracting just one in shorthand:
1 2 3 |
distance ++; //add one to distance distance --; //subtract one from distance |
Questions and Activities to Try-
Now that you feel comfortable with declaring and changing an integer variable a little, here are a couple challenges for you before you move on-1. Try using the distance variable to make Sparki move forward more and more as the loop continues but use the same variable to make Sparki wait less and less each time through the loop. (It’s ok if you get an error because a variable value goes below zero, as long as it works at least a couple times then you’re getting the hang of it.)
2. Try using multiplication (*) and division (/) to change how the value of the variable is used in various commands without changing the value of the variable.
3. Try declaring and using multiple integer variables. Use one to control how far Sparki rolls forward and the other to control how long Sparki waits before rolling forward again. Once you’ve done that try writing some code that changes both of the variable values. How about writing a command that multiplies the variable values by each other somehow?
Really, with code the possibilities are endless. Next we’ll talk about how to use variables other than just integers.