Читайте также:
|
|
Lesson 4: Control Statements - Loops
The information in this lesson will teach you the proper way to execute iterative logic with the various C# looping statements. Its goal is to meet the following objectives:
C# Simple Loops
looping is very necessary because it relieves the programmer from time consuming tasks. Developers are able to execute statements repeatedly millions of times if they need to. Tedious calculations can also benefit from loops as well. Lets see how loops can make our job easier.
Lets print the numbers from 1 to 10
Example 1:
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(1);
Console.WriteLine(2);
Console.WriteLine(3);
Console.WriteLine(4);
Console.WriteLine(5);
Console.WriteLine(6);
Console.WriteLine(7);
Console.WriteLine(8);
Console.WriteLine(9);
Console.WriteLine(10);
Console.Read();
}
}
Output
1 2 3 4 5 6 7 8 9 10
A grueling way to print from 1 to 10. Lets examine a more efficient way to do basic counting using goto.
Example 2
using System;
class Program
{
static void Main(string[] args)
{
int x = 0;
LoopLabel:
x += 1; //Equivalent to x = x + 1
Console.WriteLine(x);
if (x < 10) //if x is less than 10 then goto LoopLabel
goto LoopLabel;
Console.Read();
}
}
Output:
1 2 3 4 5 6 7 8 9 10
This is a much more efficient way to count from 1 to 10 or even a thousand or 1 million
The while Loop
A while loop will check a condition and then continues to execute a block of code as long as the condition evaluates to a Boolean value of true. Its syntax is as follows:
while (<boolean expression>) { <statements> }.
OR
while(''condition''){ <code to be executed if ''condition'' is true>}The statements can be any valid C# statements. The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.
When the boolean expression evaluates to false, the while loop statements are skipped and execution begins after the closing brace of that block of code. Before entering the loop, ensure that variables evaluated in the loop condition are set to an initial state. During execution, make sure you update variables associated with the boolean expression so that the loop will end when you want it to. Listing 4-1 shows how to implement a while loop.
Дата добавления: 2015-11-14; просмотров: 45 | Нарушение авторских прав
<== предыдущая страница | | | следующая страница ==> |
Text 9 Defining Clinical Research Informatics | | | Listing 4-2. The Do Loop: DoLoop.cs |