Professor Mustard Programming
 

Programming 101 - Unit 01 - The Basics

01b) Variables
 
Okay, understanding WriteLine() is all well and good, but if we're ever going to get anywhere, we need to get into variables. Because variables are so important in any program, we'll be covering a lot of ground here, but cheer up! Anything you learn on this page works pretty much the same in Java and C++, too. So you're actually learning something that will work in three different languages! Don't tell me that's not useful.

A variable acts as a "placeholder" in your program for an actual value. Why would we want this? In a word, flexibility. Like the "Mad Libs" word substitution game, variables allow you to plug in a value at any point in your program's execution. Why write the same code fifty times, if each time you're only changing one number? Variables become all the more important when you start getting input from the user, and need a place to store the information they supply your program. But before we drag the user into this, we'd better get a little more familiar with how variables work. Consider the following example:

string programmerName = "Professor Mustard";
Console.WriteLine("This example was written by " + programmerName + ".");



Whoo! Pretty cryptic stuff, eh? As you might remember from the previous lesson, "string" is simply a programming term for "text" (a "string" of letters, if you like). The above code would yield the following output:

This example was written by Professor Mustard.


Now that we know what we're dealing with, let's take a closer look at the line where we "declare" the variable (mention it for the first time, basically). The first word on that line, "string", tells C# that we're creating a variable of the string type (yes, there are other types, and we'll get to them in a second. Focus!) The second word, "programmerName", is an arbitrary name for the variable. Names can be pretty much any combination of letters, numbers and underscores that you want. As long as the name doesn't begin with a number, or contain any punctuation marks other than underscores, its all good. Of course, it's best if the variable's name tells you something about what it actually stores... don't call a variable "carWax" if it stores somebody's address! By extension, this also means that you should avoid ambigious, single-letter names like "x", "y" and "i" (even though you see them all the time... that doesn't mean you should make a practice of it)!

The "=" sign is how we tell C# that we're assigning an actual value into our variable, and the text in quotation marks is the value we're assigning. So, by the time this statement completes, C# knows to insert the words "Professor Mustard" everyplace in the program where it sees the programmerName variable. Changing the value in the variable is as simple as changing the value in the quotation marks.

We can also copy the value in a variable by making it "equal to" another variable of the same type. For example...

string coolProgrammer = programmerName;


"programmerName" already has a value in it from earlier, "Professor Mustard". So once this code runs, "coolProgrammer" will also have a value of "Professor Mustard". We can also overwrite the value of a variable at anytime, by using the "=" operator...

coolProgrammer = "You";


Now "coolProgrammer" stores a value of "You" (I know, flattery will get me nowhere). Note, however, that we do not include the "string" keyword at the beginning of this statement. That's because we've already "declared" coolProgrammer as a string, earlier in the program. You only need to specify a variable's datatype the first time you mention it, and if you try to announce it again, C# will get angry and yell at you. Note also that we do not need to give the variable a value right away. The following code is perfectly legal:

string profession;
profession = "carpenter";



Just remember that you're generally not allowed to use a variable until you give it a value. Anyways, enough about strings for now. Let's store some numbers! Observe the following code:

int headCount = 29;
Console.WriteLine("There are " + headCount + " people in attendance.");



An "int" is a numeric integer, that is, a whole number with no decimal value. It's perfect for any situation where decimal numbers aren't required (a decimal-numbered headcount could get pretty messy; who wants fractions of heads floating around?) As you can see, you can output it to the console in pretty much the same manner as a string.

You can even convert string values to integers, but beware! The operation will only work if the entire string is a valid integer value. For example, "10", "-412", and "38899" would all convert to integer format just fine. "meow", "-34-", and even "100 meow" would not. And if a conversion operation fails, your program will crash: no apologies, no warnings, just "boom". Later on, we'll learn of ways to handle this, but for now, just be careful when converting strings to integers. Here's how you do it:

string someNumberText = "123";
int convertedNumber = Convert.ToInt32(someNumberText);
Console.WriteLine("I converted the number " + convertedNumber + " from a string!");



It's also worth noting that you convert basically any datatype to a string, by using it's ToString() method. For example:

string convertedString = convertedNumber.ToString();
Console.WriteLine("I got this string from an int variable: " + convertedString);



Virtually every datatype imaginable has a ToString() method, which makes converting stuff back to string format extremely easy. It's not all that useful to us at the moment, but it becomes much more handy when you move beyond simple console output!

Of course, not every number in the world translates to a nice, tidy whole number. There are times when we'll need decimals, so let's look at one:

double height = 35.5;
Console.WriteLine("The height is: " + height);



We use the "double" datatype to store numbers that might have decimal values. (Historically, it's called a double because it takes up twice as much memory as an int... double, get it?) And yes, there's a Convert.ToDouble() method as well, so getting a double from a string works the same way integers do. Speaking of which, what if you have an integer value that you want to store in a double? Well, an int is basically a double that contains less information, so it's actually just as easy as:

int integerHeight = 40;
height = integerHeight;
Console.WriteLine("The height is now: " + height);



As you can see, it's possible to just plunk int values directly into doubles, with no problems. However, storing a double in an integer is a little more tricky. Because integers only store whole numbers, any decimal information in a double will be lost when it is stored in an integer. C# doesn't normally like doing this, so we have to perform a "cast" to assure the program that this is okay. Note also that C# will not bother "rounding" your double to the nearest whole number, since there are official math functions that do this (more on this later). It simply "drops" any and all decimal values.

height = 32.953;
integerHeight = (int)height;
Console.WriteLine("The integer height is now: " + integerHeight);



The (int) simply tells C#, "Look, stupid! It's an integer now!" There are also two other kinds of decimal-storing varaible, "float" and "decimal". "float" is less precise, and decimal is incredibly precise. You have to use casting when trading values between any of these three datatypes; double, float and decimal. Floats are typically faster than doubles, so you see them a lot in drawing commands. Decimals, on the other hand, come into play when absolute precision is necessary, such as dealing with money. Don't assume, however, that you should always use decimals because of their precision. Speed and efficiency are critical elements in a program, and you don't want to be storing 100,000 decimal places of information for every number when 1,000 will do. In fact, for simplicity's sake, I probably won't be mentioning either float or decimal for quite awhile.

Now for some fancy stuff. Does the following line of code look fun to read?

Console.WriteLine("Name is " + programmerName + ", height is " + height + ", headcount is " + headCount);


If you said "yes", then you probably just blurted it out to be stupid (and should probably seek help for answering a text document's question out loud). That line is really quite horrible to read. Between all the quotes and "+" signs, it's hard to figure out what's actually going on. Wouldn't it be nicer if we could have an uncluttered message, and just put all that variable crap at the end? For example, like this?

Console.WriteLine("Name is {0}, height is {1}, headcount is {2}", programmerName, height, headCount);


This statement outputs exactly the same thing as the previous one, except you get to stick all your variables at the end. All your actual text needs is a little placeholder wherever you want to insert one of the variables mentioned at the end of the list. {0} represents the first variable at the end of the statement, {1} represents the second variable, and so on. There is no limit to the number of variables you can tack on to the end, either!

Okay, two more tricks and we're done. You can declare multiple variables at once like this...

int a, b, c, d;


...and assign one value to several variables at once like this:

a = b = c = d = 100;


There we go. Of course, as nice as this variable stuff is, the program's still going to say the same thing each time it runs, unless the programmer changes the actual code. It's time to start getting input from the user. But first, a code sample:



using System;

namespace B_Variables
{
  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
      // Declare a string variable to hold some text
      string programmerName = "Professor Mustard";
      Console.WriteLine("This example was written by " + programmerName + ".");

      // Copy the contents of one variable into another
      string coolProgrammer = programmerName;
      Console.WriteLine(coolProgrammer + " is a cool programmer!");

      // Store an integer
      int headCount = 29;
      Console.WriteLine("There are " + headCount + " people in attendance.");

      // Convert string to integer
      string someNumberText = "123";
      int convertedNumber = Convert.ToInt32(someNumberText);
      Console.WriteLine("I got the number " + convertedNumber + " from a string!");

      // Convert integer to string
      string convertedString = convertedNumber.ToString();
      Console.WriteLine("I got a string from an int variable: " + convertedString);

      // Store a decimal number
      double height = 25.8;
      Console.WriteLine("The height is: " + height);

      // We can also overwrite the value in a variable whenever we want
      height = 58.32;
      Console.WriteLine("The height is now: " + height);

      // Store an int value in a double
      int integerHeight = 40;
      height = integerHeight;
      Console.WriteLine("The height is now: " + height);

      // Store a double value in an int (requires casting)
      height = 32.953;
      integerHeight = (int)height;
      Console.WriteLine("The integer height is now: " + integerHeight);

      // You can add as many variables to your output as you like!
      // Ugly way
      Console.WriteLine("Name is " + programmerName + ", height is " + height + ",   headcount is " + headCount);
      // Nice way
      Console.WriteLine("Name is {0}, height is {1}, headcount is {2}", programmerName, height, headCount);

      // Declare multiple variables
      int a, b, c, d;

      //Assign one value to several variables
      a = b = c = d = 100;
      Console.WriteLine("a={0}, b={1}, c={2}, d={3}", a, b, c, d);

      // Force the program to stay up until the user hits "ENTER"
      Console.ReadLine();
    }
  }
}