Loops in C# and VFP
C#
While, Do While, Continue, Break
|
VFP
Do While, Loop, Exit, EndDo
|
Both languages have a loop which will execute as long as an expression remains true. The
syntax, apart from the use of braces in C#, is similar in both languages.
C# Syntax Notes
C sharp has two forms of while loop, one starts with the
While statement and has the test at the start of the loop.
Both these examples will ask the user for a password until "secret" is entered. The first
loop needs to have the value of pwd initialised before the start of the loop because the
test needs to be able to find a value for its comparision:
string pwd = "";
while (pwd !="secret")
{
Console.WriteLine("Enter the password...");
pwd = Console.ReadLine();
}
The other starts with the Do statement and has the test
at the end of the loop. In this case we don't need to initialise the pwd string. The user
will have given us a value by the time that we get to the test at the end of the string:
string pwd;
do
{
Console.WriteLine("Enter the password...");
pwd = Console.ReadLine();
}
while (pwd !="secret");
The drawback of the second form of the loop structure is that we're always going to
execute the code in the body of the loop at least once and sometimes this isn't what we
want to happen.
Use the break keyword to break out of the loop early and
continue execution after the end of the loop. In this password example we might want to
increment a counter and abandon the loop after three attempts.
Use the continue keyword to cut short an iteration and to
return to the start of the loop.
VFP Syntax Notes
FoxPro just has the loop with While
at the beginning so it is not possible to initialise the test condition inside the body
of the loop.
pwd = ""
Do while pwd !="secret"
pwd="InputBox("Enter the password...")
EndDo
Use the Loop keyword to skip the rest of the code in the
loop and return immediately to the test in the While
statement. Use the Exit command to break out of the loop and
execute the statement following EndDo.
FoxPro does however have another specialist type of loop command. The
scan
command is specifically designed for processing data in tables.
Case
|
Language index
|
For
|