When You Know How Many Times To Loop

FOR Loop

The FOREACH loop is for looping through collections. The WHILE and DO…WHILE loops are for looping until a condition is no longer valid. Sometimes you know exactly how many times you want to loop through a code block. It is at these times when you would use a FOR loop.

The way a FOR loops works is that it initializes a new variable that it will use to determine how many times the loop will occur. This variable usually has an integer datatype. It also uses a statement that determines how the variable value will change each time the loop executes. In between the initialization statement and the incrementation statement, is the condition check that tells the loop when to stop.


The syntax of the FOR loop looks like this:


FOR keyword (variable initialization; condition check; incrementation statement)

{

Code Block

}

Code Example:

 for (int i = 1; i < 5; i++)
 {
 Console.WriteLine(i);
  }

Variable Initialization

The variable initialization is the first code statement that is executed in a FOR loop. This code statement is where you declare and initialize any variables that are going to be used to control the loop. In our example, an integer variable is created and given the value of zero. Naming conventions don’t apply for the variables of a FOR loop, the majority of FOR loops you will see use a variable named “i”. If it helps, think of it as the “i” in “iterator”, since it controls the iteration of the loop.


The variable can be initialized with any value that you feel your loop needs. You will see examples later in this post with the initialization using different starting values.

This step is only done a single time. It is processed when the application first reaches the FOR loop.


Condition Check

After the variable is initialized, the condition check is evaluated. As with the value of the variable, the condition check can be whatever you feel is need to control the iterations of your FOR loop. Generally, the condition will involve the variable you initialized in the first step.


In our example, the condition check resolves to TRUE while the variable value is less than 5. You will see examples of different condition checks later in this post.

The condition check is evaluated before every iteration of the loop. If the condition resolves to FALSE, the loop will not execute.


Incrementation Statement

If the value of the iterator variable never changes, the condition check will always resolve to TRUE. If there is no chance for it to resolve to FALSE, you will create an “infinite” loop. As I explained in the post regarding WHILE loops, infinite loops should be avoided.

The incrementation statement does what the name implies. This code statement will update the value of the iterator variable after the code block of the loop has been executed.


Walkthrough

Let’s walk through precisely what the application would do when it reaches our example FOR loop.


  • Creates a variable and assigns it a value of 1

  • Checks to see the value is less than 5; Resolves to TRUE

  • Displays 1 in the console window

  • Increases the value of the variable by 1; the value is now 2

  • Checks to see the value is less than 5; Resolves to TRUE

  • Displays 2 in the console window

  • Increases the value of the variable by 1; the value is now 3

  • Checks to see the value is less than 5; Resolves to TRUE

  • Displays 3 in the console window

  • Increases the value of the variable by 1; the value is now 4

  • Checks to see the value is less than 5; Resolves to TRUE

  • Displays 4 in the console window

  • Increases the value of the variable by 1; the value is now 5

  • Checks to see the value is less than 5; Resolves to FALSE

  • Exits the FOR loop.

FOR Loop Examples

Let’s imagine you are creating a shopping list application for a store that only allows you to buy ten items at a time. A FOR loops could help you ensure the user follows that rule.

 Console.WriteLine("Welcome to my store, TOP TEN.");
 Console.WriteLine("It's time to go shopping.");
 List<string> items = new List<string>();
 
 for (int i = 1; i < 11; i++)
 {
 Console.WriteLine("What would you like to buy?");
 items.Add(Console.ReadLine());
 }
 
 Console.WriteLine("You have reached your limit of items.");

For our next example, we have a game where the user has a limited amount of hours to survive. Every turn takes up one hour. A FOR loop will allow us to set that limit. However, this time we want our variable value to start high and decrease with every iteration of the loop.

 Console.WriteLine("You are playing \"Last Breath\".");
 int hoursToLive = 7;
 Console.WriteLine("A game where every hour matters.");
 Console.WriteLine($"You have {hoursToLive} hours to live."); 
 
 for (int i = 7; i > 0; i--) 
 {
 Console.WriteLine($"You have {i} hours left.");
 // Game Code
 Thread.Sleep(1000);
 Console.WriteLine("An hour goes by.....");
 Thread.Sleep(1000);
 Console.WriteLine("You feel your energy draining....");
 Thread.Sleep(1000);
 }
 
 Console.WriteLine("You have died.");

Changing the Iterator

If you recall from the blog post about the FOREACH loop, you were told that you could not add or remove items from the collection you were looping through, affecting the number of times the loop iterates once it starts.


The same logic does not apply to the FOR loop. You can add any logic you want inside of the loop that could change the value of the iteration variable. You can add or subtract from the variable, thereby increasing or decreasing the number of times the loop iterates.

For example, if we wanted to provide a way for the user to survive longer in the “Last Breath” game, we could add logic that changes the iteration variable.

 bool drankMedicine = false;
 
 for (int i = 7; i > 0; i--) 
  {
 Console.WriteLine($"You have {i} hours left.");
 Thread.Sleep(1000);
 if (i == 2 && drankMedicine == false)
 {
 i += 3;
 Console.WriteLine("You found some medicine that give you 3 extra hours of life.");
 drankMedicine = true;
 }
 Thread.Sleep(1000);
 Console.WriteLine("An hour goes by.....");
 Thread.Sleep(1000);
  Console.WriteLine("You feel your energy draining....");
 Thread.Sleep(1000);
 }

The code has been updated to allow a one-time use of medicine which increased the number of times the loop iterates.

Jump Statements

In C#, there are a few keywords that allow you to redirect the flow of the application. These keywords are known as “jump statements” since they let you jump from the current application flow and transfer control to a different section of the code. There are five different jump statements in C#, but we are only going to discuss two of them in this post. The other ones will be discussed in future posts.


BREAK

Technically, you have already been introduced to the BREAK statement. If you recall, it is used when you use SWITCH…CASE logic.

 switch (user emotion)
 {
 case "happy":
 Console.WriteLine("I'm happy you're happy");
 break;
 default:
 Console.WriteLine("I'm sorry you're not happy");
 break;
 }

The BREAK keyword is used to “break” out of the current code block and transfer control of the application to the code that follows the block.


The SWITCH…CASE statement requires the BREAK statement so that the application knows when the matched CASE is complete.


You can also use a BREAK to break out of a loop if something occurs that should skip the rest of the loop iterations.


Let’s go back to our code for the “Top Ten” store that limits the number of items a user can buy. The maximum number of items they can buy is ten, but what if they only want two items, or maybe seven. The current code does not handle that situation, but we can use a BREAK to update it.

 for (int i = 1; i < 11; i++)
 {
 if (i > 1)
 {
 Console.WriteLine("Would you like another item? (Y/N)");
 string answer = Console.ReadLine();
 if (answer.Equals("n",StringComparison.OrdinalIgnoreCase) )
 {
  break;
 }
 }
 
 Console.WriteLine("What would you like to buy?");
 items.Add(Console.ReadLine()); 
 }
 if (items.Count < 10)
  {
 Console.WriteLine($"You have purchased {items.Count} items.");
 }
 else
 {
 Console.WriteLine("You have reached your limit of items.");
 }

The code has been updated to allow the user to stop shopping any time before they reach the 10 item limit. Once they enter the character “n,” the BREAK keyword is reached, and the application jumps out of the loop.


Labeled Statements

Before you understand GOTO, you need to know about “labeled statements.”

A labeled statement is an identifier you create in your code that will allow the application to transfer the flow of the code immediately following the label.


You create a labeled statement by typing the label you wish to use, followed by a colon.

 Greeting:
 Console.WriteLine("Hello, what is your name?");
 string userName = Console.ReadLine();
 
 NumberGame:
 Console.WriteLine("Would you like to play a game?");
 string answer = Console.ReadLine();
 
 GameExit:
 Console.WriteLine("Press any key to exit the application...");
 Console.ReadKey();

This code has three labeled statements: “Greeting”, “NumberGame”, and “GameExit”.

The vital thing to understand is that without a GOTO statement to jump to the different labels, this code will execute as if the labels aren’t there. The application will start with the greeting and proceed to the exit code.


GOTO

The GOTO keyword allows you to force the application to jump to a labeled statement in your code. GOTO can be used within any code block to transfer control of the application, including loops.


Let’s update our “Last Breath” game with some GOTO statements to give our player a chance to survive.

for (int i = 7; i > 0; i--)
 {
 Console.WriteLine($"You have {i} hours left.");
 Console.WriteLine("What is the three-digit number to call for help?");
 switch (Console.ReadLine())
 {
 case "911":
 Console.WriteLine("Did you really think it would be that easy?");
  Console.WriteLine("Your mistake cost you an additional hour.");
 i--;
 break;
 case "245":
 Console.WriteLine("You have successfully called for help.");
  goto Survival;
 default:
 Console.WriteLine("That is not the right number.");
 break;
 }
 Thread.Sleep(1000);
 Console.WriteLine("An hour goes by.....");
 Thread.Sleep(1000);
 Console.WriteLine("You feel your energy draining....");
 Thread.Sleep(1000);
 }
 
 Console.WriteLine("You have died.");
 goto ExitGame;
 
 Survival:
 
 Console.WriteLine("Help arrives in the nick of time.");
 Console.WriteLine("You will live to play another day.");
 
 ExitGame:
 Console.WriteLine();
 Console.WriteLine("I hope you enjoyed this fun, upbeat game.");
 Console.WriteLine("Press any key to exit the application...");
 Console.ReadKey();

Our game has been updated with labels and GOTO statements. There are a few things I want to point out.


Missing BREAK?

Notice in our SWITCH…CASE that there is no BREAK keyword in the case for “245”.

 case "245":
 Console.WriteLine("You have successfully called for help.");
  goto Survival;

Remember, BREAK is a jump statement used to jump out of the CASE. Since GOTO is also a jump statement, BREAK is not needed.


Missing GOTO?

The next thing you should notice is that there is not a GOTO statement after the “survival” code like there is after the FOR loop.

 Console.WriteLine("You have died.");
 goto ExitGame;
 
 Survival:
 
 Console.WriteLine("Help arrives in the nick of time.");
 Console.WriteLine("You will live to play another day.");
 
 ExitGame:

We need the application to jump to ExitGame after our death message. If we don’t jump at that point, the code after the “Survival” label will execute as well.


However, we don’t need to add a GOTO statement after the survival message since the application will naturally execute that code next.

34 views0 comments

Recent Posts

See All