Variables
Learn how to initialize, store, and manipulate variables

 

What are Variables?

Variables are a way to store information in a program. The easiest way to think of them is as if they were boxes. In these boxes we can store stuff and we can write a name on the box to help us know which box is the one we want. One box can be named kitchen and has plates in it, another could be named books and has books in it, of course another could be named blankets and has lamps in it. With variables we can do the same thing.

This creates a variable named “values” and puts the number 6 into it. We can also store more than just numbers.

This one creates a variable named “letters” and stores the letter ‘S’ into it. You may notice that with values we started with “int”, but then with letters we started with “char”. That first word tells it what type of information will be stored in the variable. There are three main types that we will be using:

    int: numbers from -32,768 to 32,767

    char:  letters (it really holds number that represent letters)

    byte: numbers from -128 to 127

We only need to have the data type labeled when we create the variable, not every time we use it, for example in this code:

We do not need the int the second time since we already created the variable.

Also we can set variables equal to other variables.

Or even to themselves (with some math too):

Here is an example program using variables:

At the top of the code we created two variables, A and B. Then inside of setup we started the communication with the Serial monitor (Serial.begin(9600);). Then inside of loop we have a few things happening. Firstly we add one to A every time through the loop (A = A + 1;), then we print out the value of A onto the Serial monitor. Next we set B to half of A (B = A / 2;), and then print it out onto the screen. Then we have a short delay of 0.1 seconds to slow down the loop so that we can see what is happening (delay(100);). If we run this program and watch the Serial monitor we can see the values of A going up by one every time, and B always being half of A. To open the Serial monitor click on the magnifying glass in the top right corner.