Difference between revisions of "Loop"
esse quam videri
(Created page with " =Definition= =Relevance= =Explanation= =Resources= == See also == ==Notes== ==External Links== Category:Programming Language Concepts Category:Object Orient...") |
|||
Line 4: | Line 4: | ||
=Relevance= | =Relevance= | ||
− | = | + | =Examples= |
+ | Below are examples of loops in C# | ||
+ | Do-While Loop: This type of loop will always run at least once because it will not check the termination condition until after the first run. | ||
+ | <syntaxhighlight lang ="csharp"> | ||
+ | string choice; // This will be used to store the user's input. | ||
+ | bool validSelection; // This will be used to terminate the loop. | ||
+ | do | ||
+ | { | ||
+ | |||
+ | console.WriteLine("Which path will you take? 1 or 2?"); | ||
+ | choice = console.ReadLine(); | ||
+ | |||
+ | if(choice == "1" || choice == "2") // checking to see if the choice is valid. | ||
+ | { | ||
+ | validSelection = true; // valid choice, no longer need to loop. | ||
+ | } | ||
+ | else | ||
+ | { | ||
+ | validSelection = false; // invalid choice. Because the variable is set to false, it will cause the loop to repeat, meaning that the user will be asked to make a choice again. | ||
+ | } | ||
+ | |||
+ | } while(validSelection == false) // if validSelection is set to false, repeat the loop. | ||
+ | </syntaxhighlight> | ||
Revision as of 16:02, 21 August 2019
Definition
Relevance
Examples
Below are examples of loops in C# Do-While Loop: This type of loop will always run at least once because it will not check the termination condition until after the first run.
string choice; // This will be used to store the user's input.
bool validSelection; // This will be used to terminate the loop.
do
{
console.WriteLine("Which path will you take? 1 or 2?");
choice = console.ReadLine();
if(choice == "1" || choice == "2") // checking to see if the choice is valid.
{
validSelection = true; // valid choice, no longer need to loop.
}
else
{
validSelection = false; // invalid choice. Because the variable is set to false, it will cause the loop to repeat, meaning that the user will be asked to make a choice again.
}
} while(validSelection == false) // if validSelection is set to false, repeat the loop.