Looping Commands


C#, like any other programming language, has commands that can control the execution flow of a program. The term "looping command" is a general term common in the programming community. It is used to describe commands that put a program into a loop. Most programming languages support some form of looping command. Why are such commands important?

Allow me to illustrate. Just in case you haven't noticed, streetlights automatically turn on if the level of sunlight is low and automatically shuts off when the sun is back. Assuming that we have been given the task to write a program that would detect the change in sunlight level, how would you do it?

We would probably have the main logic of the program to say the following;

  1. as long as the sunlight level is low, leave the lights on

  2. as long as the sunlight level is high, leave the lights off

Just looking at the statements, you can immediately tell that we need some form of loop to constantly check for sunlight levels. The next challenge is how do we express real-life requirements in a C# program? C# has four looping commands available. For those familiar with C/C++ programming, these commands will look familiar.

Before we begin, a just a few simple reminder. In the context of this article, we shall also use the term "command" and "statement" to loosely mean the same thing and remember that a boolean expression is required in most of these looping statements, which means the expression must either return true or false. The C/C++ assumption that any non-zero value is considered true (even negative numbers) no longer holds true in C#.

The first command off the rank is the while command, whose syntax is as follows:

while (Boolean-expression ) {body}

To illustrate the use of the while command, we will use a simple counter algorithm, which we will also use as an example in other looping commands. The following is an example of a while command in C#.

nCounter = 0;
while ( nCounter < 100 ) {
nCounter = nCounter + 1;
}

The while command tests the condition first before executing body, which is enclosed in two curly braces. If the condition is true, then the body is executed otherwise command flow is transferred to the end of the while statement, which is the next command after the closing curly brace. A semicolon at the end of the brace is not required.

Related to the while command is the do-while. It's syntax is as follows:

The copyright of the article Looping Commands in C# Programming is owned by Jose Aniceto. Permission to republish Looping Commands in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic