Variables

Let's now learn about variables. They are like data storage containers in your program, each one with its own name. We can put, for instance, a number inside a variable and then later retrieve it, manipulate it and change its value. In this case, in any place in the software that you would use a number (such as 0 or 255 or 800), you can use the name of this variable.

!Declaring a variable

There are two parts in declaring a variable: a name and a type. Once you have chosen the type and name of the variable, you can declare it like:

int example_variable; // Declaring an int variable, with the name example_variable

There are various kinds of variables and the one we're going to use in this project is int! The int is a variable that stores integer numbers, negative or positive.

There are a few coding rules for naming variables: the name cannot start with a number and cannot contain spaces or special characters. Variable names can only be composed of 0-9, az, AZ, and _. When you are choosing a name for the variable, try to make it descriptive, that is, choose a name such as "yellowLed" instead of "variableX". This will help making the code easier to read and to be interpreted later.

As a general rule, a variable can only be used within the curly braces ({}) it has been declared. However, you can create a global variable, declaring it before the setup() function.

The global variables can be accessed from any point in the program. Nevertheless, keep in mind that, if you create a variable inside setup(), it will be only possible to use it inside setup(), and the same thing applies to loop().

!Using a variable

In order to give a value to a variable, you can used the attribution operator =. The attribution operator uses the value at the right-hand side of the equal sign and stores it inside the variable at the left-hand side.

Example:

// Declaring the variable
int goals_from_Germany;

// Attributing the value
goals_from_Germany = 7;

We can also give the value directly when we create a variable:

int goals_from_Brazil = 1; 

(Notice that in the previous experiment, we used a variable to store the value of the pin that was related to the component : int yellowLed= A1;)

!Think!

Is it possible to make mathematical operations using more than one variable?

Answer

Yes, it is possible, check out the example:

int a = 15;
int b = 72;
int c = a * b;  /* c equals 15×72 */  

Below you can see the mathematical operators:

Mathematical Operators Code Representation
Sum +
Subtraction -
Multiplication *
Division /
Remainder of division %