Start course
Difficulty
Intermediate
Duration
23m
Students
411
Ratings
5/5
Description

Structures to repeat tasks or access data collections are at the heart of compact and reusable code. C#, like other programming languages, provides three basic mechanisms allowing you to execute statements multiple times dynamically. In this course, we'll take an in-depth look at the for loop, while loop, and foreach loop.

These looping mechanisms vary in structure and intended application, and we'll examine how to use them in different scenarios. In the course of this detailed investigation, you will learn some of the potential pitfalls that accompany programming with each type of loop, how to avoid them, and create efficient loops. There are code examples demonstrating the use of each loop type in a practical way, along with other helpful C# and .NET code snippets.

Learning Objectives

  • An in-depth understanding of for loops
  • Learn about while loop syntax and see how they are used
  • Gain a foundational understanding of object lists
  • Learn how to use, and not to use, a foreach loop to iterate through a list

Intended Audience

This course is intended for those who already have a basic understanding of C# and want to learn about loops.

Prerequisites

To get the most out of this course, you should have a basic knowledge of C# as well as an understanding of object orientation and C# classes. Please consider taking our Introduction to Object Orientation and C# Classes course before taking this one.

Source Code

Source code related to the lectures can be found here

Transcript

The while loop could be considered the ultimate in loop simplicity. Essentially, repeat some action, do some stuff until I say otherwise. The syntax is while followed by some Boolean condition that evaluates to true, within brackets and the body of the loop enclosed in braces. Sometimes the Boolean condition may seem a little back to front. For example, while not done, keep doing, and the while condition can be arbitrarily complex. While loops are often used as placeholders, waiting for events to take place.

As an aside, in Windows, each window has an event loop that whirrs away in the background, waiting for user interaction, such as mouse clicks and keyboard presses. Within the loop, some functions will take the appropriate action when one of these events is detected. The Boolean condition for the window's event loop is something like, keep checking for events while the window is not closed.

Because the while loop is so flexible, you could use it like a for-loop where the Boolean condition checks the value of a counter variable against some numerical limit, but let's not dwell on that, as it's the domain of the for-loop.

There is a variation on the while loop called the do-while loop. Essentially, the same as a while loop, except the while condition evaluation is at the end of the loop. The keyword do begins the loop, meaning it's executed at least once no matter the condition evaluation's result. I can't recall a time I've used a do-while loop, as it doesn't add functionality that can't be achieved with a while loop.

Here I have a while loop that checks two conditions. First, we compare the current time with the Now property of .NET's DateTime object with another DateTime variable called endTime, which I've set to be five seconds in the future. The endTime value is set by using the add seconds method of the DateTime class. Secondly, I have a bool variable called finished initialized to false, and I'm using the double ampersand "and" operator to say, while endTime is greater than now and I'm not finished continue looping. As soon as either of these conditions becomes false, the loop will terminate. The state of the finished Boolean is set to true when the integer counter i equals nine. Each time through the loop, we compare i to 9 and then increment it, which is not how it reads. Next, I write out to the console the value of i and the current time formatted as hours, minutes, seconds, and milliseconds. Yes, triple f doesn't immediately spring to mind when thinking of something to represent milliseconds, but obviously, the M is taken for minutes. To introduce some delay in the execution of the loop, so we can see what's happening and the output doesn't disappear off the bottom of the screen, I'll use the sleep method. The sleep method of the system thread object takes an integer value specifying the number of milliseconds to pause the current thread's execution. To introduce some literal randomness, I'm using the Next method of the System.Random object to say return a randomly generated number between 50 and 2500. Each time round the loop execution will pause for between 50 ms and 2 ½ seconds. Okay, let's run that. We can see that the while loop has terminated because now is greater than endTime, five seconds has elapsed. Now, I'll reduce the sleep time by getting the randomly generated milliseconds to be between 10 and 500. When we rerun it, we can deduce that finished has become true because i is now ten, and if we look at the printed out times, less than five seconds has elapsed. What's interesting to note here is the order of operations when assigning the value to finished. Because 10 has been written to the console, we can assume that i is equal to 9, making finished true and then incremented by one.

On its face, while loops appear simple and straightforward, where you update the condition variable, in this case, finished, to terminate the loop. However, where you do that in relation to the other statements being executed does change the code's behavior. If I move the finished evaluation to the end of the loop, I get slightly different behavior. This simple example makes it seem obvious, but in complex code where the variable used for while loop evaluation is also used for conditional branching within the loop, it can have unexpected consequences.

About the Author
Students
21181
Courses
72
Learning Paths
14

Hallam is a software architect with over 20 years experience across a wide range of industries. He began his software career as a  Delphi/Interbase disciple but changed his allegiance to Microsoft with its deep and broad ecosystem. While Hallam has designed and crafted custom software utilizing web, mobile and desktop technologies, good quality reliable data is the key to a successful solution. The challenge of quickly turning data into useful information for digestion by humans and machines has led Hallam to specialize in database design and process automation. Showing customers how leverage new technology to change and improve their business processes is one of the key drivers keeping Hallam coming back to the keyboard. 

Covered Topics