C# If Statements, Switch Statements, For Loops, and While Loops

So far in our series, we've covereddownloading 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, syntaxerrors, the 'private' versus 'public' keywords, brace pairing, and theConsole class.

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

Well, we've covered a lot of ground in a fewbrief 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-schoolmath, 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 weaquired in previous tutorials, and as the old saying goes, "Practicemakes perfect." So if there are a few topics you aren't totally clearabout, go back and review the pertinent tutorials, but rest assuredthat I'll often review basic concepts as we continue our studiestogether. This regular revisitation will help reinforce concepts inyour mind.




Although I introduced the ifkeyword at the tail-end of the fifth tutorial, it was really only aforetaste of our full discussion about programming loops. In thislesson, Tutorial #6, we're going to discuss for loops and while loops,and we'll talk about various pitfalls that programmers can fall victimto when it comes to dealing with these incredibly useful, yet sometimestricky, 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 runtimeerrors. I'll show examples of each sort, and I'll ask you to identifywhat the problem is. This will be good practice for you. You'll be ableto take a source code listing I provide and copy/paste it directly intoyour 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 tointerview me, I'll be happy. Else, I'll apply to Yahoo. And if Yahoowon'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:

an class
="smallblack">
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 anothercondition-evaluator structure, but before we move on to it, I firstwant 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 wouldbe the following situation. Imagine that you're a college student, andthat in order to make the Dean's List you must not only have a GPA of3.3 or better, but also you must have less than four unexcused classabsences:


if((sngMyGPA >= 3.3) && (iUnexcusedAbsences < 4)){

   PlaceStudenOnDeanList();

}else{

   Console.WriteLine("Better luck next semester…");
}

In the example above, I have a variable oftype Single (holds numbers that have a decimal component) namedsngMyGPA and an integer variable named iUnexcusedAbsences. Naturally,one will hold my grade point average, while the other holds the numberof unexcused classroom absences I've had in the current semester. Youcan 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 seethat I've placed each component of the expression being evaluated inits own set of parentheses, within the broader set of parentheses thatenclose the entire expression that if is evaluating. This is agood idea, as it will help you to avoid mistakes of logic that ariseout of the particular order of operations in complex expressions.

Another situation that can arise is one inwhich we want a certain block of code to execute if either one or theother 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 ifcondition 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 thehighlighted line of code to read int x=3, y=2; and the if condition will still evaluate to true, because at least one orthe other of the integer variables equals two. However, if we changethe highlighted line of code so that x is equal to 5 and y is equal to8, the if condition evaluates to false, because neither of thevariables would then hold a value of 2, which is what is tested for inthe 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 programn");
Console.ReadLine();

}
}

The key line in this program is the highlighted line above that reads "if(!blnSick)…" The exclamation point is the logical Notoperator that tells the compiler to evaluate the negation of theblnSick variable's value. Now, remember, the code in the set of bracesthat 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 anykey other than "y", then blnSick is set to false. Then, when it isevaluated 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 ifsabove and the program would have worked fine (assuming we didn't make asyntax error). But there is a better way of handling multiple choices,and that is the switch statement, which — like the ifstatement — is a way of controlling branching behavior in a program.Personally, I prefer to use a switch statement anytime a simple if…elsewon't suffice. In other words, if we're not looking a simple either-orcase, but instead are dealing with multiple possibilities, it'sgenerally 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, separatingvalue2 and valueN. This indicates that any number of cases might lie inbetween those two. The default case contains code that is to beexecuted only if none of the other cases evaluate to true. Let meprovide a simple example to illustrate a switch statement in action.Let's say we have a program that examines the color of socks I'mwearing 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 switchstatement. Copy (or better yet, type) the above program into your IDEand run it. Notice that the program has a special retort in store forfour possible inputs the user may have in response to the sock colorquery. 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 breakkeyword followed by a semicolon to terminate that particular case.Unlike in some other programming languages, in C# control cannot fallthrough to the next case inside a switch statement. This is a goodthing because it helps prevent some very sneaky runtime errors that canbe hard to track down.


The For loop

Without the use of if and switchstatements to control branching behavior in programs, it would beimpossible to write useful programs of any significant complexity. Ofsimilar importance are loops. Loops are sections of code that willrepeat. How many times do they repeat? Well, ideally, you control thatas the programmer. In many instances, we want our program to dosomething a specific number of times. In the following program, I'llillustrate using a for loop to print "C#, King of ProgrammingLanguages!" to the console a total of x times, where x is a number fromtwo 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 forloop 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'sgoing to have to print C#'s bragging remark to the console. Try thisprogram sever

al times, inputting various integers between 2 and 10inclusive. Notice the two if statements in the source codelisting above? They serve to put bounds on the value of x, since theuser could enter a value of -80 or +1,000. There's a more elegant wayof 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'regoing to be dealing with a loop, i.e., a section of code that executesa certain number of times before the program flow resumes at the firstline 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 becomecustomary 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 sentinelvariable is a variable that stands guard at the top of a loop and eachtime program control comes back to the beginning of the loop, thissentinel 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 theclosing brace of the loop, telling the compiler to return to the top ofthe 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 repeatsitself until our message has been written to the console a total offive times. At this point, when control returns to the top of the loopand 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 thisexplanatory video. Be forewarned that the audio quality is not thegreatest, but for those visual-learners out there, it should help yougrasp what's going on in a situation where we use a for loop in our programs.

Now, it is more often the case thatprogrammers will write their for loops by setting the sentinelvariable's initial value to zero. The code above could also be writtenlike 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 sourcecode. 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 howyou'll see it most often in others' code, and in online examples. Howwould you write a for loop that writes "C# rocks!" ten times to theconsole, and tracks the number of times the loop has iterated? Idemonstrate 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 sentinelvariable must be incremented by a value of 1 each time the looprepeats. For example, we could increment the sentinel variable inincrements of 5. Try the following program in your editor, and noticethe 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("nnPress the Enter key to end program ");
Console.ReadLine();

}//end Main

}//end class Program

It's also possible to decrement the loop'ssentinel variable's value, either by one or some other amount. Forexample, here is the countdown.cs program that mimics theten-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(){

Co

nsole.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("nnPress the Enter key to end program ");
Console.ReadLine();

}//end Main

}//end class Program

As you can see, in this example, we begin oursentinel variable at a value of ten, then decrement its value by oneeach time through the loop. When the value of i is no longergreater than zero (which happens after the tenth iteration), thecondition-test fails and the body of the loop is stepped over, withprogram 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 isno programming task in which inifinite loops make any sense. A programthat employs an infinite loop is a program that never ends (that is,until you kill it using the Task Manager or else terminate it fromwithin the IDE, if the program is being developed). Try the followingprogram which I have dubbed mobius.cs. Run it inside the IDE indebug mode, and see what happens. Before running the program, bring upthe Windows Task Manager and click on the Performance tab, making amental note of the CPU usage. Start the program, and while it isrunning, Alt-tab to the task manager and notice how the CPU Usage hasspiked. It may actually say that CPU Usage is 100%. Actually, ofcourse, it isn't quite 100%, or else you couldn't do anything withWindows.

You can then shut down the misbehaving programby clicking the VCR-style stop button in the IDE. Or, if you aredeveloping from the C# command-line compiler, alt-tab to the WindowsTask Manager, select the Applications tab, select the program, and thenclick the End Task button. Eventually, the program will error, becauseeventually the value of i, as it is repeatedly incrementedupward, will exceed the bounds of the integer variable type. You don'twant to sit there watching the program's output until this happensthough, 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 inadvertentlycreated an endless loop is when the IDE (and sometimes the rest ofWindows) becomes unresponsive or very slow, and often the screen stopsrepainting itself, or does so only very slowly. An infinite loop is nota 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 alwaysundesirable, it is also true that we don't always know ahead of timehow many times we will need a particular loop to iterate. Perhaps wehave set a condition that might become true the very first time throughthe loop, or instead might not come true until the 25th iteration, orthe 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 arealso many situations in which we want a certain block of code toexecute, continuously, while a certain condition remains true. Thereare 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 twoforms of the While loop are simply mirror images of one another.However, they are subtly different. Consider the following twoprograms, 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 notequal to zero. So,

the only real difference in the two programs is thatone uses a do…while loop and the other uses a while…do loop. Yet,perhaps surprisingly, the first program, the one using the do…whileloop, will write the statement to the console. The second program isfairly common sense. I mean, after all, we're setting x equal to zero, then almost immediately saying "while x is notequal to zero, do this…"; the first program isn't so intuitive,though. What you need to understand about that loop configuration isthat the condition test doesn't occur until the bottom of the loop.Therefore, the loop will iterate the very first time without anycondition-testing occurring. Only at the end of the first iterationdoes it test the condition, and if that condition is true, it will loopa 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.csprogram and improve upon it, after we had covered loops. It's time forme 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 entersanything besides one of those four choices. Instead, it uses a default case in the switchstatement as sort of a catch-all for inappropriate responses. What we'dlike to be able to do, though, is only accept one of the four suggestedchoices as input, and redirect the user if he types anything else. Thiscan 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 alittle, from this tutorial. Loops are a critical programming structure,in just about any programming language. Mastery of loops is likewisecritical. I hope you'll take the quiz associated with this, andprevious, tutorials, and that you'll feel free to read back throughthis document if you need a second, or even third, exposure in orderfor these concepts to sink into your noggin'. I'm going to leave youwith 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.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!