A variable is a symbolic name for (or reference to) information. The variable's name represents what information the variable contains. They are called variables because the represented information can change but the operations on the variable remain the same. In general, a program should be written with "Symbolic" notation, such that a statement is always true symbolically. For example if I want to know the average of two grades, We can write "average = (grade_1 + grade_2) / 2.0;" and the variable average will then contain the average grade regardless of the scores stored in the variables, grade_1 and grade_2.
Variables in a computer program are analogous to "Buckets" or "Envelopes" where information can be maintained and referenced. On the outside of the bucket is a name. When referring to the bucket, we use the name of the bucket, not the data stored in the bucket.
Variables are "Symbolic Names". This means the variable "stands in" for any possible values. This is similar to mathematics, where it is always true that if given two positive numbers (lets use the symbols 'a' and 'b' to represent them):
a + b > a
(i.e., if you add any two numbers, the sum is greater than one of the numbers by itself).
This is called Symbolic Expression, again meaning, when any possible (valid) values are used in place of the variables, the expression is still true.
Another example, if we want to find the sum of ANY TWO NUMBERS we can write:
result = a + b;
Both 'a' and 'b' are variables. They are symbolic representations of any numbers. For example, the variable 'a' could contain the number 5 and the variable 'b' could contain the number 10. During execution of the program, the statement "a + b" is replaced by the Actual Values "5 + 10" and the result becomes 15. The beauty (and responsibility) of variables is that the symbolic operation should be true for any values.
Another example, if we want to find out how many centimeters tall a person is, we could use the following formula: height in centimeters = height in inches * 2.54.
This formula is always true. It doesn't matter if its Joe's height in inches or Jane's height in inches. The formula works regardless. In computer terminology we would use:
height_in_centimeters = height_in_inches * 2.54; % the variable height_in_centimeters is assigned a % new value based on the current value of "height_in_inches" % multiplied by 2.54
There are only a few things you can do with a variable:
Create one (with a nice name). A variable should be named to represent all possible values that it might contain. Some examples are: midterm_score, midterm_scores, data_points, course_name, etc.
Put some information into it (destroying whatever was there before).
We "put" information into a variable using the assignment operator, e.g., midterm_score = 93;
Get a copy of the information out of it (leaving a copy inside)
We "get" the information out by simply writing the name of the variable, the computer does the rest for us, e.g., average = (grade_1 + grade_2) / 2.
Below are some examples of how to use variables:
age = 15; % set the users age age_in_months = age * 12; % compute the users age in months age_in_days = age_in_months * 30; % compute the approximate age in days student_name = 'jim'; % create a string (array of characters) grades = [77, 95, 88, 47]; % create an arary
int age = 15; // set the users age int age_in_months = age * 12; // compute the users age in months int age_in_days = age_in_months * 30; // compute the approximate age in days int grades; // create an arary
var age : int = 15; // set the users age var age_in_months : int = age * 12; // compute the users age in months var age_in_days : int = age_in_months * 30; // compute the approximate age in days var grades : Array; // create an arary variable (NO ARRAY yet)
There are 6 properties associated with a variable. The first three are very important as you start to program. The last three are important as you advance and improve your skills (and the complexity of the programs you are creating).Memorize These!
The name is Symbolic. It represents the "title" of the information that is being stored with the variable.
The name is perhaps the most important property to the programmer, because this is how we "access" the variable. Every variable must have a unique name!
The type represents what "kind" of data is stored with the variable. (See the Chapter on Data Types).
In C, Java, ActionScript, etc, the type of a variable must be explicitly declared when the name is created.
In Matlab, the type of the variable is inferred from the data put into the variable.
A variable, by its very name, changes over time. Thus if the variable is jims_age and is assigned the value 21. At another point, jims_age may be assigned the value 27.
Most of the time, when you "create a variable" you are primarily defining the variables name and type. Often (and the best programming practice) you will want to provide an initial value to be associated with that variable name. If you forget to assign an initial value, then various rules "kick in" depending on the language.
Here are the basics:
In Matlab you cannot create a variable without giving it a value. The very act of creation is associated with an assignment into the variable.
age = 20; % this creates a variable named age with the value 20 (and type Number (double)) fprintf('age is %f\n'); % answer: age is 20
In C, if you create a variable without an initial value, the initial value is GARBAGE. By garbage, we mean that the value is random and unknown. It could be 5, it could be "hello", it could be anything.
int age; printf("age is %f\n"); // answer: age is 120912312 (i.e., Garbage) age = 20; printf("age is %f\n"); // answer: age is 20
ActionScript is much nicer than C, in that it gives a well defined default value. This value is based on two things. 1) if the variable type is an object, then the variable contains "null" by default (thus no object exists in the variable until one is "newed". 2) if the variable is a number, than the value is 0.
var age : int; trace("age is " + x); // answer: "age is 0" (default 0) age = 20; // assign the value 20 to the variable age trace("age is " + x); // answer: "age is 20"
Good programs are "Chopped" into small self contained sections (called functions) much like a good novel is broken into chapters, and a good chapter is broken into paragraphs, etc. A variable that is seen and used in one function is NOT available in another section. This allows us to reuse variable names, such as age. In one function 'age' could refer to the age of a student, and in another function 'age' could refer to the vintage of a fine wine.
Further this prevents us from "accidentally" changing information that is important to another part of our program.
A Life Time
The life time of a variable is strongly related to the scope of the variable. When a program begins, variables "come to life" when the program reaches the line of code where they are "declared". Variables "die" when the program leaves the "Scope" of the variable.
In our initial programs (which do not have functions), the life time and scope of the variables will be the "entire program".
A Location (in Memory)
Luckily, we don't have to worry too much about where in the computer hardware the variable is stored. The computer (Matlab/C/Actionscript, etc., via the compiler) does this for us.
But you should be aware that a "Bucket" or "Envelope" exists in the hardware for every variable you declare. In the case of an array, a "bunch of buckets" exist. Every bucket can contain a single value.
Good variable names tell you, your teammates, (and your TA) what information is "stored" inside that variable. They should make sense to a non computer programmer. For example:
g = -9.81; % bad gravitational_constant = -9.81; % good
The Name of the variable is not the information! The name is a title of the envelope/bucket, the information is contained in the envelope/bucket. The variable can contain different pieces of information at different times.
The information in the variable should be easily manipulated:
class_size = 95; % good: tas_per_student = class_size / 3;
Notice that we can use class_size in math expressions.
% bad: Cannot Change value to represent new students (or those who withdraw!) class_size_is_95 = true;
tas_per_student = ????? !!! Cannot access the 95 value
Notice that we cannot use class_size in math expressions.
This version of the variable would tell a "person" what the class size is, but would not make that info available to the computer.
Remember, the variable should contain information (Not be the information) and the information should be easy to change.
The good way to change class size:
class_size = 100; % new value for _same_ variable
The bad way to change the class size:
"Declare another variable"
class_size_is_100 = true;
Now we have both class_size_is_100 and class_size_is_95 set to true!!! How bad is that?
One more example:
the_profs_name = 'jim'; % GOOD the_prof_is_jim = true; % BAD
"Access" a variable.
To access a variable is to "read" (or assign) the information inside the variable.
To access a variable, you simply type its name.
For example: total_age = jims_age + jens_age;
To Access an Array
To access an array is to "read" from or "store" to a single "bucket" of the array:
% In Matlab, Arrays start at index 1 % In Matlab, Arrays are indexed using parentheses () % Thus in Matlab: quiz_grades(1) = 98; average_quiz_score = ( quiz_grade(1) + quiz_grade(2) + quiz_grade(3) ) / 3.0;
// In C, Java, and Actionscript, Arrays start at index 0 // In C, Java, and Actionscript, Arrays are indexed using square brackets  quiz_grades = 98; average_quiz_score = ( quiz_grade + quiz_grade + quiz_grade ) / 3.0;
Notice how very similar the syntax is. More importantly, notice that the "SEMANTICS" is the same.
"Assign" a value to a variable.
When you assign a value to a variable, you replace the old value with a new one. The old value is gone forever. You can, and often do, replace the old value of a variable based on the current value of the variable. See the example below:
number_of_students = number_of_students + 1;
"Declare" a variable.
To declare a variable is to create the variable.
In Matlab, you declare a variable by simply writing its name and assigning it a value. (e.g., 'jims_age = 21;').
In C, Java you declare a variable by writing its TYPE followed by its name and assigning it a value. (e.g., 'int jims_age = 21;').
In ActionScript declare a variable by writing "var" followed by the name of the variable, followed by a colon, followed by the TYPE. (e.g., var jims_age : int = 21;').
"Initialize" a variable.
Initializing a variable is another way to say, "declare a variable", but further, implies giving it a base value.
For example, if we are plotting something on the X/Y axes, and we want to start at zero for Z, we would say ("x = 0;"). Thus we have "initialized" the x variable to the value 0.
"Stored" in a variable.
The information "stored" in a variable, is the last piece of information assigned to that variable name. After assigning into a variable, all previous information is lost.
Note, we often use the statement "store the value 5 in X" to mean the same as "assign the value 5 to X"