Yorkville High School Computer Science Department
Yorkville High School Computer Science Department on Facebook  Yorkville High School Computer Science Department Twitter Feed  Yorkville High School Computer Science Department on Instagram

Yorkville High School Computer Science

ASSIGNMENTS: No Current Assignments

Computer Programming I :: Lessons :: Variables

Variables

A variable is an important concept in programming. It is a storage area in the computer's memory that can be used to store words, numbers, or other types of data. You can store something in a variable so you can access it whenever you want and you can change it whenever you want. You can think of a variable as a friend who you ask to hold onto something for you.

Your Friend: the Variable

You can change the value of a variable by setting the name of the variable equal to what you want to change it to. For example:

myFriend = "SpongeBob";

myFriend = "SpongeBob"

Our variable is now storing SpongeBob. Notice that you had to put quotes around "SpongeBob." You will need to do this anytime you want to store text. You can always change the value of a variable by storing something else in it.

myFriend = "Cartman";

myFriend = "Cartman"

The variable no longer equals "SpongeBob," it is now equal to "Cartman." Whenever you write something new to a variable it replaces whatever the variable previously held. An important concept to note is that the variable is always on the left and what you are writing to it is on the right. The value you are writing to the variable can be a number, text, or the value stored in another variable.

String Variables

A string variable is a variable that can hold any symbols the computer can display. You should only use this type of variable if you have to hold characters other than numbers. Strings take up more space than other types of variables which is why you should only use them if you have to. Here are some examples of things that can be stored in a string.

The only item above that you would not want to store in a string would be 1981. Since it only contains numbers you could safely store it in a numeric variable, which we will discuss next.

Numeric Variables

There are a few different variable types that can hold numbers. An integer, or int, can hold a 32-bit signed integer. A signed integer can hold positive or negative numbers, but an integer cannot store decimal places. A 32-bit integer has a range from -2,147,483,648 to 2,147,483,648. Do you know why it is in this range?

A float, or single, is a single-precision floating point number. A floating point number can store decimal places and in the case of a single it can store up to 7 digits. A double is a double-precision floating point number, and can store up to 16 digits. Finally, a decimal has more precision than the floating point numbers, but it has a smaller range. This makes a decimal the best choice for financial calculations. You can see the range of the two float types, as well as all the other numeric variable types, in the table below.

Type Range Size/Precision
sbyte -128 to 127 Signed 8-bit
byte 0 to 255 Unsigned 8-bit
char One Keyboard Character Unicode 16-bit character
short -32,768 to 32,767 Signed 16-bit
ushort 0 to 65,535 Unsigned 16-bit
int -2,147,483,648 to 2,147,483,647 Signed 32-bit
uint 0 to 4,294,967,295 Unsigned 32-bit
long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Signed 64-bit
ulong 0 to 18,446,744,073,709,551,615 Unsigned 64-bit
float ±1.5e-45 to ±3.4e38 7 digits
double ±5.0e-324 to ±1.7e308 15-16 digits
decimal (-7.9 x 10^28 to 7.9 x 10^28) / (10^(0 to 28)) 28-29 digits

We use numeric variables as opposed to the string data type when you know that the variable will only need to store numbers. You can perform mathematical calculations on number variables using the following symbols: +, -, *, / for addition, subtraction, multiplication, and division.

Declaring Variables

Before you can use a variable you must first declare it. A variable declaration tells the compiler to reserve space in memory to hold the value of the variable. Different programming languages have slightly different methods for declaring variables.

  1. Create a new C# project called "Variables."
  2. Rename the form "frmVars."
  3. Add a button to your project.
  4. Name the button "btnConcat."
  5. Change the text of the button to "Concatenate."

We need to be able to access the code of our program in order to create a variable. This is simple to do in Visual Studio.

  1. View CodeIf the Solution Explorer is not visible go to View>Solution Explorer.
  2. Make sure the Form is highlighted and click on the View Code Button.

There isn't much to look at yet, but we are going to add our variable right under the section that says "public partial class frmVars : Form".

  1. Add the "string mood" line to your program:
public partial class frmVars : Form
{
   string mood = "happy";

The code above is very important. You will need to use it whenever you want to declare a variable. Here is what each part does:

Variable Roles

Every variable should have a purpose, and that purpose is sometimes referred to as the role of a variable. We will use the term roles to describe how variables are used as we go through this course.

The variables we have seen so far (myFriend and mood) are both known as most-recent holders. A most-recent holder is a variable that holds the latest value encountered and can go through a series of values.

myFriend is a most-recent holder because the value changes, but there is no set pattern to those changes.

While mood has not changed yet it will change in future when we write code to accept input from the user.

Below is a list of all of the variable roles. You do not have to know these now, but we will introduce them as the course progresses.

Role Informal Definition
Fixed Value A variable which is initialized without any calculation and whose value does not change thereafter.
Stepper A variable stepping through a succession of values that can be predicted as soon as the succession starts.
Most-Recent Holder A variable holding the latest value encountered in going through a succession of values.
Most-Wanted Holder A variable holding the "best" value encountered so far in going through a succession of values. There are no restrictions on how to measure which is the "best" value.
Gatherer (Accumulator) A variable accumulating the effect of individual values in going through a succession of values.
Transformation A variable that always gets its new value from the same calculation from the value(s) of other variable(s).
Follower A variable that gets its values by following another variable.
One-Way Flag A two-valued variable that cannot get its initial value once its value has been changed.
Organizer An array which is only used for rearranging its elements after initialization.
Temporary A variable holding some value for a very short time only.

Naming Variables

Just like form components, variables are easier to recognize if they have good names. The following tips are taken from the Making Good Software blog by Alberto Gutierrez.

Tip 1: Make the variable name as descriptive as possible. Don't use generic names.

Good Examples: daysDateRange, flightNumber, carColor

Bad Examples: days, dRange, temp, data, var1

Tip 2: The variable name has to be as short as possible while remaining descriptive.

Good Examples: timeToOpenDoor, materialSize

Bad Examples: howLongDoesItTakeToOpenTheDoor, howBigIsTheMaterial

Tip 3: It's okay to use abbreviations, but explain the abbreviation with a comment.

Good Example: dc // Detective Comics

Bad Example: ac

Tip 4: Use Camel Case.

Good Example: currentTextTransition

Bad Example: currenttexttransition

Tip 5: Don't use negative logic for names.

Good Example: isEnabled

Bad Example: isNotEnabled

Tip 6: Be consistent.

If you use customer as a variable name in one part of your program don't have a variable called client in another part.

Adding Code to Form Components

Now let's make our button display the value of our variable in a pop-up window known as a message box. Whenever you want to add code to a form component you simply need to double-click the form component. This creates a method based on the default event for that form component. Methods and events will be discussed later in the course.

  1. Double-click the button.
  2. Add the following code in between the curly brackets to the button click event handler:
private void btnConcat_Click(object sender, EventArgs e)

MessageBox.Show(mood, "Hello World!");
}

MessageBox is a class that allows you to create a message box. Show is a method that displays the message box you created. The method takes two parameters, or inputs. The first parameter is the text that will be displayed. In our case we want to display whatever is stored in the description variable. The second parameter is the title of the message box, which we put in quotes because it is not a variable name.

To test our program we need to compile it. Visual Basic is known as a high-level programming language, which makes it easier for people to interact with. However, the computer needs to create a running program based on machine language, which represents the 1s and 0s that control the computer hardware. A compiler takes a high-level language and converts it to machine language. We will need to compile our program to see it work.

Run Button

  1. Click the Run Button to compile your program.
  2. Pressing the button you created should make the message box pop up.
  3. Pressing the Stop Button will allow you to return to your code.

Storing Text Box Contents

When someone types something in a text box you can always access it by using the text property of that text box. However, there are many times where you will want to have a more permanent storage solution. That is where variables come in.

The Final Form

  1. Add two text boxes to your form as shown above.
  2. Change the name of the left text box to "txtFirst" and the name of the second to "txtLast".
  3. Add two labels above each text box.
  4. Change the text of the labels to "First Name" and "Last Name".
  5. Change the names of the labels to "lblFirst" and "lblLast".

We are going to create two variables to store the contents of each text box. These variables are going to exist in the button click event handler instead of the top of our code like the mood variable.

  1. Double-click the button to view its code.
  2. Declare two string variables, firstName and lastName, underneath where you declared the mood variable.
  3. Add the following two lines of code in bold ABOVE the MessageBox line in the button code.
firstName = txtFirst.Text;
lastName = txtLast.Text;

After the equal sign on the lines above we are accessing the text property by adding .Text after the name of each text box. You can access any property of any form component in this way. These two lines will store the contents of each text box in the variables when the button is clicked.

Concatenating Strings

Finally, let's add the first and last names to our Message Box. We want it to say something like "Homer Simpson is happy!" To do this we have to concatenate strings, or join strings together. To concatenate two strings you simply need to place the plus sign (+)between them.

  1. Change your MessageBox code to the following:
MessageBox.Show(firstName + " " + lastName + " is " + mood + "!", "Hello World!");

Type Casting

If you tried playing around with numeric variable types you may have noticed that you cannot use numeric variables in a message box. This is because a message box wants a string variable and the compiler will complain if you give it something else. We can get around this, though, with type casting. Type casting allows you to change a variable from one data type to another. This comes in handy a lot, but you should always consider if you are using the correct variable type when you use this feature. If you have to type cast every time you use a variable then it should probably be declared differently. While there are a number of different ways to type cast we will look at how to convert a string to a numeric type and how to convert the other way around.

To convert a numeric variable to a string simply add .ToString() after the variable name like the following example:

MessageBox.Show(num1.ToString());

Make sure you include the empty parenthesis with the ToString method or it will not work. To convert a string to a numeric type you can use the Convert method as shown below:

num1 = Convert.ToInt32(txtNum1.Text);

The Convert method contains all the numeric types so you can convert a string into any of them.

Yorkville High School Computer Science Department on Facebook Yorkville High School Computer Science Department Twitter Feed Yorkville High School Computer Science Department on Instagram