C Sharp/Loops

Lesson Goals
This lesson will focus on all types of loops in the flow of programming in C# via the console. At the end of this lesson you should be able to:
 * Understand how to use loops.
 * Understand the prerequisite condition of looping.
 * Explain the different types of loops and their specific use.
 * Understand the difference in various loops.
 * progammatically create collections that can be looped through.

Introduction
Probably in every programming language loops are there to run a specific block of code repetatively based on a specific exit condition. The exit conditon, which is nothing but a boolean expression, is checked every time before a new loop executes and it exits the loop if the condition returns false. In C# these are also present. Loops are productive, smart and clean way of writing code. In a garment factory there is only one person or machine who attach the labels to the garments one after another. You would not find as many labeler as the number of garments in the factory. The condition is, the labeler will work till there are no longer any garments available for labeling. This is a real life example of looping in action.

Types of Loops
There are mainly 4 types of loops in C#. Loops can be nested as well.
 * while loop
 * do loop
 * for loop
 * foreach loop

While Loop
Here is the basic structure of While loop. while { ... } While loop executes a block of code (here execution step1 through execution stepn) repetatively as long as the given boolean condition returns true. Before each new run it checks the condition first and if true then only a new run begins else code flow moves below the loop. Here is an example,-

Output
0 1 2 In the given example, while loop first checks if variable number is less than 3, which is the case here as number is initialized with 0. Code-flow moves into the while block and executes the first line and prints 0. On second line number value increments with 1. The new value is 1. On next run as number is still less than 3, again it prints number as 1. Similarly, third time it prints 2. Now after increment number value is 3. This makes the while condition false and flows out of the loop without executing the inner block of code.

Do Loop
Do loop or in other words Do-while loop is similar to while loop but the difference is it checks the boolean condition at the end of the execution block. That way, it is guaranteed to run at least once. On the other hand, since while loop validates the boolean condition at the begining of the execution block, there is no guarantee that the inner block of code will run, unless you programmatically do so. Here is the structure of do loop, - do { ... } while; Please note, unlike while loop here you need to put that semi-colon at the end of the while statement.

The typical use of do loop is when you want to show some message or menu to the user and want some input after that. So that it runs at least once and based on the input the loop may or may not run again. Here is an example, - It is a typical example of do loop.

For loop
First let us have a look at the structure of the for loop. for (counter-initialization; counter-bound; counter-increment) { ... } Here are the steps of for loop,- As you can see, for loops are useful when you know exactly how many times the looping should occur. Also, you must have noticed that the counter-bound gets checked before the execution steps gets executed. so, like while loop, for loop also executes zero or more times. Also note, all the expressions of the for loop are optional. Below is an infinite for loop example. Now lets see a for loop in action, -
 * 1) First counter-initialization happens. This is an one time operation for the life of the loop.
 * 2) Then counter-bound gets checked. This is another boolean condition and as long as it evaluates to true code-flow moves to the next step. Else it will move out of the loop.
 * 3) Now execution step1 through execution stepn gets performed.
 * 4) Next counter-increment happens.
 * 5) Again step-2 executes.

Output
1 3 5 7 9 The above example has one special thing. It has two disruptions in the otherwise smooth run of for loop execution block. As you have already learned about the branching statements the two if sections uses break and continue to breakaway from the execution block.

Foreach loop
This type of loop is typically used to iterate through a collection of objects. There are many .NET provided collection objects available for use, such as, Arraylist. The major difference between a for loop and a foreach loop is that, for loop repeats a block of code for a number of times, where as foreach loop repeats a block of code for each item in a collection of objects. Here is a structure of foreach, - foreach (  in ) {     ...    } Here type is the datatype of each element that is there in the collection. The iteration variable is the meaningful name for each element. The list is the collection on which the iteration will happen. And there is these repeatable block of code from execution step 1 through execution step n.

Points to Remember: -
 * 1) Not all collections can be iterated using foreach. In fact a collection has to have implementation of System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(T) interface.
 * 2) The in keyword and type definition is required.
 * 3) While iterating through a collection using foreach, the collection is read only. This means any items in that collection can not be modified in the foreach execution block. However, if you are using custom types like collection class or structs then you can modify individual fields in that. More on this in later lessons.

Foreach in System Collections
Let's have a look at a simple example of a foreach loop using system defined collection object, an array.

Output
0 1 1 2 3 5 8 13 Here we have an integer array populated with the first 8 numbers of Fibonacci Series. Then in the foreach loop we printed each element in each line. Here the looping is possible as the system defined collection array by default implements System.Collections.IEnumerable.

Foreach in Custom Collections
Usually custom collections do not support looping through foreach. Trying so will throw compile time error. So to enable foreach looping for a class we need to implement System.Collections.IEnumerable. Our class in initial form,- This throws compile time error, - foreach statement cannot operate on variables of type 'ForEachLoopApp.Splitter' because 'ForEachLoopApp.Splitter' does not contain a public definition for 'GetEnumerator' So now we need to implement System.Collections.IEnumerable.

Output
This is C# Learning Lesson 8 Loops.

Here both the interfaces IEnumerable and IEnumerator are implemented. To avoid this hassle you can use of Generic Classes. There by default System.Collections.Generic.IEnumerable(T) is implemented and it will directly iterate through foreach loop.

Performance Tips
Since foreach iterates through objects of a collection, it is slower than for loop, which is looping based on counter. Still sometimes you would have to use foreach over for.

Practice Exercises

 * Create a program that takes input as 'n' and prints the Fibonacci series till that 'n'-th position. Which loop will you use here and why? extend this program to provide the user the option to choose series from a list of series, like, Fibonacci Series, AP Series, GP Series.
 * Create a program that would take a date as input and would print all dates prior to that date in that month with the day of the week in the following format, -

MM/DD/YYYY DayofTheWeek.
 * Create a person class that can hold data in the following format,-

FirstName=john

LastName=Doe

Age=31

Address=123, Jackson Row, 50505

FirstName=Mary

LastName=Ann

Age=62

Address=20, Hill Road, 12345

You can add more data to that class collection.Then take the person FirstName as input and search the person's information and print on screen.