Using variables

It is often helpful to use as few concrete numbers or texts as possible. An example illustrates the meaning and usefulness of variables.

Following are two program versions for drawing vertical line patterns:

Variante A Variante B
line(0, 0, 0, 100);

line(10, 0, 10, 100);

line(20, 0, 20, 100);

line(30, 0, 30, 100);

line(40, 0, 40, 100);

int x;

int y1;

int y2;

int distance;

distance = 10;

x = 0;

y1 = 0;

y2 = 100;

line(x, y1, x, y2);

x = x + distance;

line(x, y1, x, y2);

x = x + distance;

line(x, y1, x, y2);

x = x + distance;

line(x, y1, x, y2);

x = x + distance;

line(x, y1, x, y2);

x = x + distance;

The variant A offers in very short form the possibility to create a line pattern. It has the major disadvantage that changes and subsequent adaptation are very difficult to implement. For example, the requirement to change the distance between the lines can only be met by adjusting each line of the code.

Variant B is much longer in the first moment, but allows a simple change of the pattern. Moreover, as will be shown later, the representation can be varied much more easily.

The basic element of variant B is the variable. Instead of using fixed values in the program code, variables are used. These variables can be used with almost any name in the program. For this they must first be declared.

1. Step: Declare a name for the variable

The instruction „int x;“ creates a integer variable with the name x .

2. Step: Initalizing the variable x with a value

Now it must be determined which numerical value hides behind a name. The line „x = 0;“ ensures that the name x stands for the numerical value 0 starting at this line. The variable x is assigned the value 0.

3. Step: Use of the variable

Now the variable can be used to For example, to draw a line:

line(x, y1, x, y2); // equals line(0, y1, 0, y2) if x is set to 0

Or to change the contents of the variable:

x = x + distance; // equals x = 0 + 20; → x = 20; if x is 0

 

Leave a Reply