Difference between revisions of "Loop"

esse quam videri
Jump to: navigation, search
(Examples)
 
(7 intermediate revisions by the same user not shown)
Line 1: Line 1:
  
 
=Definition=
 
=Definition=
 +
A loop is a set of instructions that is repeated a desired amount of times. The instructions that will be repeated lie within the curly braces { } .There are a few types of loops, each one is best-suited for a type of scenario.
  
 
=Relevance=
 
=Relevance=
 +
Loops are a common tool, with purposes ranging from searching through containers (e.g. lists, arrays, stacks, etc.) to continuously showing a console game's menu.
  
 
=Examples=
 
=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. Good for when you're absolutely sure the loop should run at least ONCE'''
  
 
<syntaxhighlight lang ="csharp">
 
<syntaxhighlight lang ="csharp">
// 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.
 
 
// This example will loop through an example game's prompt for a player to make a choice. Until the player makes a valid choice, the loop will continue asking the for the player's input.
 
// This example will loop through an example game's prompt for a player to make a choice. Until the player makes a valid choice, the loop will continue asking the for the player's input.
 +
 
string choice; // This will be used to store the user's input.
 
string choice; // This will be used to store the user's input.
bool validSelection; // This will be used to terminate the loop.
+
bool valid; // This will be used to terminate the loop.
do
+
 
 +
do // start with a do and the curly braces. See below for "while" portion.
 
{
 
{
 
 
     console.WriteLine("Which path will you take? 1 or 2?"); // prompt for asking the user.
 
     console.WriteLine("Which path will you take? 1 or 2?"); // prompt for asking the user.
 
     choice = console.ReadLine(); // getting the user's input.
 
     choice = console.ReadLine(); // getting the user's input.
Line 20: Line 22:
 
     if(choice == "1" || choice == "2") // checking to see if the choice is valid.
 
     if(choice == "1" || choice == "2") // checking to see if the choice is valid.
 
     {
 
     {
         validSelection = true; // valid choice, no longer need to loop.
+
         valid = true; // valid choice, no longer need to loop.
 
     }
 
     }
 
     else
 
     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.
+
         valid = 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.
+
} while(valid == false) // while( condition)  e.g. variable <= 10, variable != true, variable > 0
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 +
'''While Loop: This type of loop will run while the condition is true. Unlike Do-While loops, While loops are not guaranteed to run at least once (depending on the condition). More commonly used than Do-While loops.'''
 +
<syntaxhighlight lang ="csharp">
 +
// This example loops through an imaginary game while the player has lives.
 +
 +
int lives= 3;
 +
 +
// while(condition) is how to start a while loop.
 +
while(lives> 0) // if lives == 0, the loop will not execute again.
 +
{
 +
    playGame();
 +
}
 +
</syntaxhighlight>
 +
'''For Loop: This type of loop will run the specified number of times. Typically used for iterating through collections such as arrays or lists.'''
 
<syntaxhighlight lang ="csharp">
 
<syntaxhighlight lang ="csharp">
// For Loop: This type of loop will run the specified number of times. Typically used for iterating through collections such as arrays or lists.
+
// This example will look at an array of names and shuffle them. Suppose this will determine who the winner of a raffle will be.
// This example will look at a list of names and shuffle them. Suppose this will determine who the winner of a raffle will be.
+
 
string[] raffleNames= {Adam, Ben, Charile, Derek, Erik, Frank };
+
string[] raffleNames= { "Adam", "Ben", "Charile", "Derek", "Erik", "Frank" };
 
string tempName; // When shuffling, a temporary variable will be needed in order to prevent losing data.
 
string tempName; // When shuffling, a temporary variable will be needed in order to prevent losing data.
 
Random r = new Random(); // Random is a class available in C# that allows for generating random numbers. Great for our purposes of shuffling!
 
Random r = new Random(); // Random is a class available in C# that allows for generating random numbers. Great for our purposes of shuffling!
for(int i = 0; i < raffleNames.Length; i++)
+
int randomNumberGenerated; // Although Random can generate a random number, we'll be using this integer to store that generated number.
 +
 
 +
for(int i = 0; i < raffleNames.Length; i++) // The way to setup a for loop is (Initialization; Condition; Increment / Decrement)  usually increment / decrement is variable++ or variable--
 
{
 
{
 
+
    randomNumberGenerated = r.Next(raffleNames.Length); // r.Next is a function that accepts an integer as an argument to determine the range. raffleNames.Length is a property of the array that is an integer, that's what we're using for the argument.
 +
    tempName = raffleNames[i];
 +
    raffleNames[i] = raffleNames[randomNumberGenerated];
 +
    raffleNames[randomNumberGenerated] = tempName;
 
}
 
}
</syntaxhighlight>
 
  
=Resources=
+
randomNumberGenerated = r.Next(raffleNames.Length);
== See also ==
+
string winner = raffleNames[randomNumberGenerated];
 +
console.WriteLine(winner);
  
 +
</syntaxhighlight>
 +
'''Foreach Loop: This type of loop will run through all elements of a collection.'''
 +
<syntaxhighlight lang ="csharp">
 +
// This example will look at a list of contacts in a phone, attempt to find a match for a search, and state whether the search was successful or not.
  
==Notes==
+
list<string> contacts; //Suppose this was not empty.
 +
string search; // What we are trying to find in the list of contacts.
 +
bool success; // this will be the boolean that will determine if the search was successful.
  
 +
success= false; // we are setting this to false before the loop so that if the variable is true after the loop, we know there is a success.
 +
foreach(string name in contacts) // the way to setup a foreach loop is    foreach(dataType temporaryIdentifierForLoop in container)
 +
{
 +
    if(name == search)
 +
    {
 +
        success= true;
 +
    }
  
==External Links==
+
}
  
 +
</syntaxhighlight>
  
  

Latest revision as of 19:04, 28 August 2019

Definition

A loop is a set of instructions that is repeated a desired amount of times. The instructions that will be repeated lie within the curly braces { } .There are a few types of loops, each one is best-suited for a type of scenario.

Relevance

Loops are a common tool, with purposes ranging from searching through containers (e.g. lists, arrays, stacks, etc.) to continuously showing a console game's menu.

Examples

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. Good for when you're absolutely sure the loop should run at least ONCE

// This example will loop through an example game's prompt for a player to make a choice. Until the player makes a valid choice, the loop will continue asking the for the player's input.

string choice; // This will be used to store the user's input.
bool valid; // This will be used to terminate the loop.

do // start with a do and the curly braces. See below for "while" portion.
{
    console.WriteLine("Which path will you take? 1 or 2?"); // prompt for asking the user.
    choice = console.ReadLine(); // getting the user's input.

    if(choice == "1" || choice == "2") // checking to see if the choice is valid.
    {
        valid = true; // valid choice, no longer need to loop.
    }
    else
    {
        valid = 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(valid == false) // while( condition)   e.g. variable <= 10, variable != true, variable > 0

While Loop: This type of loop will run while the condition is true. Unlike Do-While loops, While loops are not guaranteed to run at least once (depending on the condition). More commonly used than Do-While loops.

// This example loops through an imaginary game while the player has lives.

int lives= 3;

// while(condition) is how to start a while loop.
while(lives> 0) // if lives == 0, the loop will not execute again.
{
    playGame();
}

For Loop: This type of loop will run the specified number of times. Typically used for iterating through collections such as arrays or lists.

// This example will look at an array of names and shuffle them. Suppose this will determine who the winner of a raffle will be.

string[] raffleNames= { "Adam", "Ben", "Charile", "Derek", "Erik", "Frank" };
string tempName; // When shuffling, a temporary variable will be needed in order to prevent losing data.
Random r = new Random(); // Random is a class available in C# that allows for generating random numbers. Great for our purposes of shuffling!
int randomNumberGenerated; // Although Random can generate a random number, we'll be using this integer to store that generated number.

for(int i = 0; i < raffleNames.Length; i++) // The way to setup a for loop is (Initialization; Condition; Increment / Decrement)   usually increment / decrement is variable++ or variable--
{
    randomNumberGenerated = r.Next(raffleNames.Length); // r.Next is a function that accepts an integer as an argument to determine the range. raffleNames.Length is a property of the array that is an integer, that's what we're using for the argument.
    tempName = raffleNames[i];
    raffleNames[i] = raffleNames[randomNumberGenerated];
    raffleNames[randomNumberGenerated] = tempName;
}

randomNumberGenerated = r.Next(raffleNames.Length);
string winner = raffleNames[randomNumberGenerated];
console.WriteLine(winner);

Foreach Loop: This type of loop will run through all elements of a collection.

// This example will look at a list of contacts in a phone, attempt to find a match for a search, and state whether the search was successful or not.

list<string> contacts; //Suppose this was not empty.
string search; // What we are trying to find in the list of contacts.
bool success; // this will be the boolean that will determine if the search was successful.

success= false; // we are setting this to false before the loop so that if the variable is true after the loop, we know there is a success.
foreach(string name in contacts) // the way to setup a foreach loop is     foreach(dataType temporaryIdentifierForLoop in container)
{
    if(name == search)
    {
        success= true;
    }

}