Search Forum
(57243 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

If Statements, Switch Statements, For Loops, and While Loops
By Bryan Miller

Welcome to the 6th tutorial in the "C# for the Completely Uninitiated" series. If you haven't already done so, you should go here and view the preceding tutorials before beginning this lesson.




So far in our series, we've covered downloading and installing the free Visual C# 2005 Express Edition IDE, basic variable types, methods (including the crucial 'Main' method), properties, classes, objects, comments, encapsulation, instantiation, namespaces, assemblies, the 'static' keyword, using references, syntax errors, the 'private' versus 'public' keywords, brace pairing, and the Console class.

We've also looked at code folding in the IDE, getting input from the console, the assignment operator, string concatenation, guidelines for naming your variables, initialisation of variables, string interpolation, try-catch blocks, method return types, the 'using' statement as a shortcut to fully qualified namespace references, accessors and mutators as precursor's to C#'s get/set property methods, constructors, base versus derived classes, and polymorphism through inheritance using virtual and overridden methods.

Well, we've covered a lot of ground in a few brief tutorials! So much so, that you may be feeling a bit dizzy, especially if you're new to programming, or at least new to the object-oriented paradigm. If that is the case, I want to reassure you. Just like in high-school math, as we go along we're going to build upon what we have learned before, but at the same time we'll continue to practice using those skills we aquired in previous tutorials, and as the old saying goes, "Practice makes perfect." So if there are a few topics you aren't totally clear about, go back and review the pertinent tutorials, but rest assured that I'll often review basic concepts as we continue our studies together. This regular revisitation will help reinforce concepts in your mind.




Although I introduced the if keyword at the tail-end of the fifth tutorial, it was really only a foretaste of our full discussion about programming loops. In this lesson, Tutorial #6, we're going to discuss for loops and while loops, and we'll talk about various pitfalls that programmers can fall victim to when it comes to dealing with these incredibly useful, yet sometimes tricky, programming structures.

Not only will I be discussing loops, but we'll also talk about the two different kinds of errors you can get when programming: syntax errors versus runtime errors. I'll show examples of each sort, and I'll ask you to identify what the problem is. This will be good practice for you. You'll be able to take a source code listing I provide and copy/paste it directly into your IDE to try it out. When you get an angry retort from the compiler, you'll have the opportunity to figure out what it didn't like.




Okay, let's get started! I have touched briefly before on the if statement. In a recent tutorial, I gave examples of everyday examples of if decision-making. Below, I give some additional real-world examples, and I provide sample code that parallels each statement:


If Statements
if I lose ten pounds, I can get into my high-school bluejeans.

if(iCurrentWeight <= (iOriginalWeight - 10)){
    highschool_jeans.Wear();
}

if the stock market crashes, Wall Street will panic.

if (blnStockMarketCrashed){
    BenBernanki.FreakOut();
}

if the temperature drops to minus ten degrees overnight, our water pipes will burst.

if (iTemperature <= -10){
    pipes.FreezeAndBurst();
}

if we get at least $2500 in our tax return, we'll pay off the car; otherwise, we'll apply it toward our credit card debt.

if (iReturnAmt >= 2500){
    car.PayOff();
} else {
    creditcard.PayDown();
}


As you can see, the basic structure of an if statement is:

if (condition){
    // do this ...
}

The condition must evaluate to true in order for the code between the curly braces to execute. If the condition evaluates to false, the code will never run. For example, examine the following code, and tell me whether or not "The number x is greater than zero." will ever be printed to the console:



01 using System;
02
03 class Program{
04
05   static void Main(){
06
07      int x=0;
08
09      if(x > 0){
10
11         Console.WriteLine("The number x is greater than zero.",  x);
12         
13
14      } else {
15
16         Console.WriteLine("The condition \"x > 0\" was not met.");
17
18
19      }//end if
20
21      Console.ReadLine();
22
23   }//end method Main
24
25}//end class Program


Hopefully, you answered "No". The output you'll get when you run the program looks like this:

The problem lies in line 7 of the program, where we both declare and initialise an integer variable named x:

int x=0;

Because we initialise the value of x to zero, and do not modify that value, the condition "x > 0" necessarily evaluates to false, so the output you'll get on the console will come from the code contained in the braces of the else keyword: "The condition "x > 0" was not met."

Our example program illustrates that the basic if statement can be expanded to incorporate an else, so that the program does something specific when the condition evaluates to false:


if (condition){
    // do this ...
} else {
    //do this other stuff...
}

It's even possible to have multiple elses in an if condition test. For example, if we were to take the following real-world scenario...

"If Google agrees to interview me, I'll be happy. Else, I'll apply to Yahoo. And if Yahoo won't have me, I'll try Cisco Systems. If none of them are interested, I'll swallow my distaste and apply to Microsoft."

...and turn it into code, we'd have something like this:



using System;

class Program{

    static void Main(){

          string employer = "";
          Console.Write("Who agreed to interview you? ");
          employer = Console.ReadLine().Trim().ToLower();

          if(employer=="google"){

              Console.WriteLine("You go, Googlemeister!");

          }else if(employer=="yahoo"){

	        Console.WriteLine("You're a rowdy Yahooligan!");

          }else if(employer=="cisco"){

	        Console.WriteLine("So, Cisco seems interested, eh?");
 
          }else{

	       Console.WriteLine("Let's hope Bill Gates likes you...");
  
          }//end if

          Console.ReadLine();

    }//end method Main

}//end class Program

 

 

Logical And, Or, & Not
We're getting ready to learn about another condition-evaluator structure, but before we move on to it, I first want to discuss the use of logical Or, logical And, and logical Not. These logic operators, when used in conjunction with an if statement, enable you to control your program's flow with greater finesse. I'll first explain logical And. Examine the following plain-English statement, then look at how I translate it into a code snippet:

If you have both a gun, and some ammunition, you can target practice.

We could evaluate two boolean variables' values to ascertain whether to invoke the TargetPractice() method:



if(blnHaveGun && blnHaveAmmo){
   TargetPractice();
}else{
   Console.WriteLine("No target practice today..."); }

In the above code snippet, both boolean variables would have to have true values in order for the TargetPractice() method to be invoked.

Another example of logical And would be the following situation. Imagine that you're a college student, and that in order to make the Dean's List you must not only have a GPA of 3.3 or better, but also you must have less than four unexcused class absences:



if((sngMyGPA >= 3.3) && (iUnexcusedAbsences < 4)){
   PlaceStudenOnDeanList();
}else{
   Console.WriteLine("Better luck next semester..."); }

In the example above, I have a variable of type Single (holds numbers that have a decimal component) named sngMyGPA and an integer variable named iUnexcusedAbsences. Naturally, one will hold my grade point average, while the other holds the number of unexcused classroom absences I've had in the current semester. You can see that the if statement checks to ensure that my GPA is at least 3.3 and, i.e., &&, that I have fewer than four unexcused classroom absences. You can see that I've placed each component of the expression being evaluated in its own set of parentheses, within the broader set of parentheses that enclose the entire expression that if is evaluating. This is a good idea, as it will help you to avoid mistakes of logic that arise out of the particular order of operations in complex expressions.

Another situation that can arise is one in which we want a certain block of code to execute if either one or the other of two conditions is met:

using System;

class Program {
    
    static void Main(string[] args) {
    
        int x = 2, y = 2;

        if (x == 2 || y == 2) {

            Console.WriteLine("Either x or y (or perhaps both) is equal to two.");

        } else {

            Console.WriteLine("Neither one of the variable holds the value 2.");

        }

        Console.WriteLine("\nPress the Enter button to exit program");
        Console.ReadLine();

    }
}

In the above program example, the if condition evaluates to true because at least one of the two variables, x or y, is equal to two (in fact, both are). We could change the highlighted line of code to read int x=3, y=2; and the if condition will still evaluate to true, because at least one or the other of the integer variables equals two. However, if we change the highlighted line of code so that x is equal to 5 and y is equal to 8, the if condition evaluates to false, because neither of the variables would then hold a value of 2, which is what is tested for in the if condition test.

Sometimes, what we want is to test whether two values are not identical. In this case, we use the logical Not operator. For example, "If you are not sick tomorrow, get in your car and drive to work." Translated into an example program, this might look like this:


using System;

class Program {
    
    static void Main(string[] args) {

        bool blnSick = false; //an initialized boolean variable
        string sKeyEntered = ""; //an initialized string variable to hold input from keyboard

        Console.Write("\nIf you are sick, press the Y key, otherwise press any other key > ");
        sKeyEntered = Console.ReadLine().Trim().ToLower();

        Console.WriteLine(); //skip a line for readability

        if (sKeyEntered == "y") {
            blnSick = true;
        } else {
            blnSick = false;
        }

        if (!blnSick) {
            Console.WriteLine("\nYou get into your car and drive to work...");
        } else {
            Console.WriteLine("You call in sick, then crawl back into bed.  Poor baby...");
        }

        Console.WriteLine("\nPress the Enter button to exit program\n");
        Console.ReadLine();

    }
}

The key line in this program is the highlighted line above that reads "if(!blnSick)..." The exclamation point is the logical Not operator that tells the compiler to evaluate the negation of the blnSick variable's value. Now, remember, the code in the set of braces that immediately follow an if(condition) test will only be executed if that condition evaluates, overall, to true. If the user instructs the program that he is not sick, by entering any key other than "y", then blnSick is set to false. Then, when it is evaluated in the if statement, it's prefaced by the logical Not operator, i.e., !, meaning "not the value held in blnSick" or, in other words, true.

Kinda tricky, huh? Lemme give you a few if statements that make use of the logical Not operator, and you decide if they evaluate to true or false:

Example A:


int x = 3;
int y = 5;

if(x != y){
   Console.WriteLine("x is not equal to y");
}

Example B:


int x = 3;
int y = 5;
x = x + 2;

if(x != y){
   Console.WriteLine("x is not equal to y");
}

Example C:


int x = 3;
int y = 5;
x = y;

if(x != y){
   Console.WriteLine("x is not equal to y");
}

 

 

 

...scroll down for answers... 

 

 

A.   (x != y) evaluates to true, because x equals 3, y equals 5, and 3 does not equal 5

B.   (x != y) evaluates to false, because we add 2 to x, result in x holding a value 5, which equals y's value of 5

C.   (x != y) evaluates to false, because we assign x the value of y, so that both variables now hold the value 5 and are therefore equal

 

 


 

 

The switch statement
As you can see, if...else if...else can handle multiple choices. We could have included several more else ifs above and the program would have worked fine (assuming we didn't make a syntax error). But there is a better way of handling multiple choices, and that is the switch statement, which -- like the if statement -- is a way of controlling branching behavior in a program. Personally, I prefer to use a switch statement anytime a simple if...else won't suffice. In other words, if we're not looking a simple either-or case, but instead are dealing with multiple possibilities, it's generally better to use switch. The syntax of such a statement in C# looks like this:


switch(value){

   case value1:
      //code goes here
      break;

   case value2:
      //code goes here
      break; 

   .
   .
   .

   case valueN:
      //code goes here
      break;

   default:
      //code goes here
      break;

} //end switch statement

Notice the vertical ellipsis above, separating value2 and valueN. This indicates that any number of cases might lie in between those two. The default case contains code that is to be executed only if none of the other cases evaluate to true. Let me provide a simple example to illustrate a switch statement in action. Let's say we have a program that examines the color of socks I'm wearing and makes some witty remark about them:


using System;

class Program{

    static void Main(){

        string sSockColor = "";

        Console.Write("Please enter red, blue, green, or black for sock color: ");

        sSockColor = Console.ReadLine();

        switch(sSockColor.Trim().ToLower()){

        case "red":
            Console.WriteLine("Feeling irritable today, are we?");
            break;

        case "blue":
            Console.WriteLine("Awww, are we feeling a bit blue today?");
            break;

        case "green":
            Console.WriteLine("What is this, St. Patrick's Day!?");
            break;

        case "black":
            Console.WriteLine("You need to add some color to your ensemble.");
            break;

        default:
            Console.WriteLine("You shouldn't be allowed to dress yourself...");
            break;

        }//end switch statement   

    }//end method Main

}//end class Program


For now, the program serves adequately to illustrate the use of the switch statement. Copy (or better yet, type) the above program into your IDE and run it. Notice that the program has a special retort in store for four possible inputs the user may have in response to the sock color query. And if the user inputs anything else, the default case handles it.

There are a couple of things you need to remember about a switch statement in C#: first of all, it's always a good idea to include a default case at the end of the statement, just before the closing brace. Secondly, every case must have a break keyword followed by a semicolon to terminate that particular case. Unlike in some other programming languages, in C# control cannot fall through to the next case inside a switch statement. This is a good thing because it helps prevent some very sneaky runtime errors that can be hard to track down.


The For loop
Without the use of if and switch statements to control branching behavior in programs, it would be impossible to write useful programs of any significant complexity. Of similar importance are loops. Loops are sections of code that will repeat. How many times do they repeat? Well, ideally, you control that as the programmer. In many instances, we want our program to do something a specific number of times. In the following program, I'll illustrate using a for loop to print "C#, King of Programming Languages!" to the console a total of x times, where x is a number from two to ten entered by the user. If you wish, type it into your C# editor and name it "kingsharp.cs":


using System;

class Program{

    static void Main(){

        int x = 0;

        try{
               Console.Write("Brag how many times? (specify 2 to 10): ");

               x = Int16.Parse(Console.ReadLine());

               if(x < 2){ x=2; }

               if(x > 10){ x=10; }

               Console.WriteLine();

               for(int i=1; i<=x; i++){

                   Console.WriteLine("C#, King of Programming Languages!");

               }//end for loop

               Console.Write("\nPlease press Enter to end program ");


           } catch (Exception e) {

               Console.WriteLine(e.Message);

           }

    }//end method Main

}//end class Program


Now, this program effectively illustrates the use of the for loop to repeat a specific block of code a particular number of times. Notice that the program does not know until runtime how many times it's going to have to print C#'s bragging remark to the console. Try this program several times, inputting various integers between 2 and 10 inclusive. Notice the two if statements in the source code listing above? They serve to put bounds on the value of x, since the user could enter a value of -80 or +1,000. There's a more elegant way of doing this, but I can't show it until I familiarize you with the while loop.

Let's examine the syntax of the for loop. To do that, I'll use a very simple example that causes "Hello, World!" to be printed to the Console five times:


for(int i=1; i<=5; i++){
   Console.WriteLine("Hello, World!");
}

Now let's take a closer look:



for(int i=1; i<=5; i++){
   Console.WriteLine("Hello, World!");
}

The for keyword tells us that we're going to be dealing with a loop, i.e., a section of code that executes a certain number of times before the program flow resumes at the first line of code immediately after that looping block.

How many times the loop executes depends upon what is contained inside the parentheses:


for(int i=1; i<=5; i++){
   Console.WriteLine("Hello, World!");
}

Notice that inside those parentheses, we declare an integer variable named i. We could have named it something else, but it's sort of become customary to use the letter "i". This variable is known as the loop sentinel. A sentinel in real life is a guard, and in programming, a sentinel variable is a variable that stands guard at the top of a loop and each time program control comes back to the beginning of the loop, this sentinel variable's value has been changed by the code inside the loop. The sentinel variable then compares its value against some other value, to determine if it will allow execution to enter the loop again.

In the loop above, we set i's initial value to 1 :


for(int i=1; i<=5; i++){
   Console.WriteLine("Hello, World!");
}

The next thing that happens is that the condition i<=5 is checked. Since 1 is less than 5, the condition evaluates to true, and so program control enters the body of the loop, and the WriteLine() method gets invoked for the first time. The very next line is the closing brace of the loop, telling the compiler to return to the top of the loop. It does so, and sees i++, which tells it to increment the value of i by one. Thus, now i is equal to 2. The compiler takes this new value of i and compares it against the condition i<=5. Again, this evaluates to true, so the body of the loop gets executed again, and we write "Hello, World!" to the console screen a second time. This process repeats itself until our message has been written to the console a total of five times. At this point, when control returns to the top of the loop and i is incremented by one, its value becomes six, which does not satisfy i<=5. Therefore, the body of the loop is skipped over, and execution resumes with the first line of code following the for loop.

You can see this looping in action. I've shown an example of that very thing in this explanatory video. Be forewarned that the audio quality is not the greatest, but for those visual-learners out there, it should help you grasp what's going on in a situation where we use a for loop in our programs.

Now, it is more often the case that programmers will write their for loops by setting the sentinel variable's initial value to zero. The code above could also be written like this, and would produce the same on-screen results:


using System;

class Program{

    static void Main(){

        Console.WriteLine();

        for(int i=0;i<5;i++){
            Console.WriteLine("C# Rules!");
        }//end for loop

        Console.Write("\nPress the Enter key to end program ");
        Console.ReadLine();

    }//end Main

}//end class Program


Note that two things change in the source code. First, the initial value of our sentinel variable is set to zero, rather than one. Second, the condition-test is now i<5 instead of i<=5. Either way works, but I recommend using this latter because that's how you'll see it most often in others' code, and in online examples. How would you write a for loop that writes "C# rocks!" ten times to the console, and tracks the number of times the loop has iterated? I demonstrate below:


using System;

class Program{

    static void Main(){

        int lineNum = 0;

        Console.WriteLine();

        for(int i=0;i<10;i++){
            lineNum = i+1;
            Console.WriteLine("C# Rules!   (line # " + lineNum.ToString() + ")");
        }//end for loop

        Console.Write("\nPress the Enter key to end program ");
        Console.ReadLine();

    }//end Main

}//end class Program


There's no rule stating that a loop's sentinel variable must be incremented by a value of 1 each time the loop repeats. For example, we could increment the sentinel variable in increments of 5. Try the following program in your editor, and notice the output:


using System;

class Program{

    static void Main(){

        Console.WriteLine();

        for(int i=0;i<=50;i+=5){
            Console.Write(i.ToString() + "\t");
        }//end for loop

        Console.Write("\n\nPress the Enter key to end program ");
        Console.ReadLine();

    }//end Main

}//end class Program

It's also possible to decrement the loop's sentinel variable's value, either by one or some other amount. For example, here is the countdown.cs program that mimics the ten-second countdown at NASA when the space shuttle is about to launch. You'll note something you may not have seen before, i.e. the System.Threading.Thread.Sleep() method. This is just something we can use to create variable-length pauses in the execution of our console-mode programs:


using System;

class Program{

    static void Main(){

        Console.WriteLine();

        Console.WriteLine("\nTower to shuttle: \"We're showing all systems are a go...\"");
        System.Threading.Thread.Sleep(2500);

        Console.WriteLine("\nShuttle to tower: \"Roger that!  We're green across the board here...\"");
        System.Threading.Thread.Sleep(2500);

        Console.WriteLine("\nTower to shuttle: \"Roger, shuttle.  Initiating countdown...\"\n");
        System.Threading.Thread.Sleep(2500);

        for(int i=10;i>0;i--){
            Console.Write(i.ToString() + "\t");
            System.Threading.Thread.Sleep(750);
        }//end for loop

        Console.WriteLine("Blast off !!\n");

        Console.Write("\n\nPress the Enter key to end program ");
        Console.ReadLine();

    }//end Main

}//end class Program

As you can see, in this example, we begin our sentinel variable at a value of ten, then decrement its value by one each time through the loop. When the value of i is no longer greater than zero (which happens after the tenth iteration), the condition-test fails and the body of the loop is stepped over, with program flow resuming at the first line of code following the loop, Console.WriteLine("Blast off !!\n");

There are two types of programmers in the world: those who have written infinite loops, and those who are going to write infinite loops at some point in time ;) An infinite loop is one from which program control never leaves.

Like the Energizer® bunny, the loop just keeps going, and going, and going...

Infinite loops are always an error. There is no programming task in which inifinite loops make any sense. A program that employs an infinite loop is a program that never ends (that is, until you kill it using the Task Manager or else terminate it from within the IDE, if the program is being developed). Try the following program which I have dubbed mobius.cs. Run it inside the IDE in debug mode, and see what happens. Before running the program, bring up the Windows Task Manager and click on the Performance tab, making a mental note of the CPU usage. Start the program, and while it is running, Alt-tab to the task manager and notice how the CPU Usage has spiked. It may actually say that CPU Usage is 100%. Actually, of course, it isn't quite 100%, or else you couldn't do anything with Windows.

You can then shut down the misbehaving program by clicking the VCR-style stop button in the IDE. Or, if you are developing from the C# command-line compiler, alt-tab to the Windows Task Manager, select the Applications tab, select the program, and then click the End Task button. Eventually, the program will error, because eventually the value of i, as it is repeatedly incremented upward, will exceed the bounds of the integer variable type. You don't want to sit there watching the program's output until this happens though, because it will take a good while...


using System;

class Program{

    static void Main(){

        for(int i=0; i>-1; i++){
            //Everybody sing: "this is the loop that never ends..."
            Console.WriteLine("Loop iteration #" + i.ToString());
        }

    }//end Main

}//end class Program

What signals me that I've inadvertently created an endless loop is when the IDE (and sometimes the rest of Windows) becomes unresponsive or very slow, and often the screen stops repainting itself, or does so only very slowly. An infinite loop is not a syntax error, because the compiler catches all errors of that type for us. Rather, an infinite loop is an example of a runtime error. You don't necessarily know anything is wrong with your program until you actually compile and run it.

Now, although infinite loops are always undesirable, it is also true that we don't always know ahead of time how many times we will need a particular loop to iterate. Perhaps we have set a condition that might become true the very first time through the loop, or instead might not come true until the 25th iteration, or the 52nd, or the 200th, etc. For such indefinite loops, it is possible, though awkward and inelegant, to use the for keyword and create a special for loop. It's much better, though, to use a while loop, which is what we'll discuss next.

 

While Loops
We find lots of everyday examples of "while"


  • "While you're in the grocery store, buy me a gallon of milk."
  • "While I'm talking, you be quiet!"
  • "While it's raining, let's stay inside."
  • "While the cat is away, the mice will play."
Likewise, in computer programming, there are also many situations in which we want a certain block of code to execute, continuously, while a certain condition remains true. There are two basic forms that While loops take, and they are...


While (condition) {
   //do this...
}

...and...


Do {
   //do this...
} while (condition)

At first blush, it appears that these two forms of the While loop are simply mirror images of one another. However, they are subtly different. Consider the following two programs, which differ only in the fact that one uses a do...while loop, while the other uses a while...do loop:

Program whiletest.cs


using System;

class Program
{
static void Main()
{
            int x = 0;

            Console.WriteLine(); //skip line, for readability

            do{

                 
                 Console.Write("I can't believe it's not butter!");
                 

            } while (x != 0);

            Console.WriteLine();

	    }
}//end class Program

Try the program listed above in your C# editor, then try the following program:

Program whiletest2.cs


using System;

class Program
{
static void Main()
{
            int x = 0;

            Console.WriteLine(); //skip line, for readability

            while (x!=0){

                 
                 Console.Write("I can't believe it's not butter!");
                 

            } 

            Console.WriteLine();

	    }
}//end class Program

Note: In a While...Do loop, the "Do" is implied, but is not actually part of the code.

You probably noticed that in both of the above programs, the integer variable, x is assigned a value of zero. And, in both programs, the condition tested for is x != 0, i.e., x being not equal to zero. So, the only real difference in the two programs is that one uses a do...while loop and the other uses a while...do loop. Yet, perhaps surprisingly, the first program, the one using the do...while loop, will write the statement to the console. The second program is fairly common sense. I mean, after all, we're setting x equal to zero, then almost immediately saying "while x is not equal to zero, do this..."; the first program isn't so intuitive, though. What you need to understand about that loop configuration is that the condition test doesn't occur until the bottom of the loop. Therefore, the loop will iterate the very first time without any condition-testing occurring. Only at the end of the first iteration does it test the condition, and if that condition is true, it will loop a second time, and so on. Here's the upshot that you need to remember:

A Do...While loop will always execute at least once, but a While...Do loop might never execute.

I said earlier in this tutorial that I would come back to the socks.cs program and improve upon it, after we had covered loops. It's time for me to make good on that promise. There wasn't anything wrong, particularly, with socks.cs, but it asks the user to enter red, blue, green, or black, yet fails to redirect the user if he enters anything besides one of those four choices. Instead, it uses a default case in the switch statement as sort of a catch-all for inappropriate responses. What we'd like to be able to do, though, is only accept one of the four suggested choices as input, and redirect the user if he types anything else. This can be accomplished quite effectively with a Do...While loop. See if you can come up with something along those lines on your own, then check out my solution below:


using System;

class Program{

    static void Main(){

        string sSockColor = "";

        do{

                Console.Write("\nEnter red, blue, green, or black for sock color, or \"quit\" to exit the program: ");
        
                sSockColor = Console.ReadLine().Trim().ToLower();
                Console.WriteLine();
        
                switch(sSockColor.Trim().ToLower()){
        
                case "red":
                    Console.WriteLine("Feeling irritable today, are we?");
                    break;
        
                case "blue":
                    Console.WriteLine("Awww, are we feeling a bit blue today?");
                    break;
        
                case "green":
                    Console.WriteLine("What is this, St. Patrick's Day!?");
                    break;
        
                case "black":
                    Console.WriteLine("You need to add some color to your ensemble.");
                    break;
        
                default:
                    if(sSockColor != "quit"){
                        Console.WriteLine("You shouldn't be allowed to dress yourself...");
                    }
                    break;
        
        
        
                }//end switch statement

                Console.WriteLine();
   
        } while (sSockColor != "quit");

    }//end method Main

}//end class Program

Well, I hope that you've benefited, at least a little, from this tutorial. Loops are a critical programming structure, in just about any programming language. Mastery of loops is likewise critical. I hope you'll take the quiz associated with this, and previous, tutorials, and that you'll feel free to read back through this document if you need a second, or even third, exposure in order for these concepts to sink into your noggin'. I'm going to leave you with this live demonstration of a program that exemplifies the use of the for loop. To view the source code, go here. As ever, I welcome any feedback you may wish to impart.