C Sharp/Loops

From Wikiversity
< C Sharp(Redirected from CSharp Input)
Jump to: navigation, search

Lesson Goals[edit]

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[edit]

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[edit]

There are mainly 4 types of loops in C#.

  • while loop
  • do loop
  • for loop
  • foreach loop

Loops can be nested as well.

While Loop[edit]

Here is the basic structure of While loop.

while(<boolean condition>)
{
 <execution step1>
 <execution step2>
 ...
 <execution stepn>
}

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,-

using System;
 
namespace WhileLoopApp
{
    class Program
    {
        static void Main()
        {
            int number = 0;
 
            while(number < 3)
            {
                Console.WriteLine(number);
                number ++;
            }
 
            Console.ReadLine();
        }
    }
}

Output[edit]

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[edit]

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
{
 <execution step1>
 <execution step2>
 ...
 <execution stepn>
} while(<boolean condition>);

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, -

using System;
namespace DoLoopApp
{
 class Program
 {
    public static void Main()
    {
        string myChoice;
 
        do
       {
            // Print A Menu
            Console.WriteLine("My Address Book\n");
 
            Console.WriteLine("A - Add New Address");
            Console.WriteLine("D - Delete Address");
            Console.WriteLine("M - Modify Address");
            Console.WriteLine("Q - Quit\n");
 
            Console.WriteLine("Choice (A,D,M or Q): ");
 
            // Retrieve the user's choice
            myChoice = Console.ReadLine();
 
            // Make a decision based on the user's choice
            switch(myChoice)
            {
                case "A":
                case "a":
                    Console.WriteLine("You want to add an address.");
                    // Put Address adding code here.
                    break;
                case "D":
                case "d":
                    Console.WriteLine("You want to delete an address.");
                    // Put Address deleting code here.
                    break;
                case "M":
                case "m":
                    Console.WriteLine("You want to modify an address.");
                    // Put Address modifying code here.
                    break;
                case "Q":
                case "q":
                    Console.WriteLine("Bye.");
                    break;
                default:
                    Console.WriteLine("{0} is not a valid choice", myChoice);
                    break;
            }
 
            // Pause to allow the user to see the results
            Console.Write("press Enter key to continue...");
            Console.ReadLine();
            Console.WriteLine();
        } while (myChoice != "Q" && myChoice != "q"); // Keep looping until the user wants to quit
    }
 }
}

It is a typical example of do loop.

For loop[edit]

First let us have a look at the structure of the for loop.

for (counter-initialization; counter-bound; counter-increment)
{
  <execution step1>
  <execution step2>
  ...
  <execution stepn>
}

Here are the steps of for loop,-

  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.

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.

for (; ; )
{
    // ...
}

Now lets see a for loop in action, -

using System;
 
namespace ForLoopApp
{
 class Program
 {
    public static void Main()
    {
        for (int i=0; i < 20; i++)
        {
            if (i == 10)
                break;
 
            if (i % 2 == 0)
                continue;
 
            Console.Write("{0} ", i);
        }
        Console.ReadLine();
    }
 }
}

Output[edit]

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[edit]

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 (<''type''> <''iteration variable''> in <''list''>)
 {
    <''execution step 1''>
    <''execution step 2''>
    ...
    <''execution step n''>
 }

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[edit]

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

using System;
namespace ForEachLoopApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] fibArray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
            foreach (int ele in fibArray)
            {
                System.Console.WriteLine(ele);
            }
            System.Console.ReadLine();
        }
    }
}

Output[edit]

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[edit]

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,-

using System;
 
namespace ForEachLoopApp
{
    class Splitter//:IEnumerable
    {
        private string[] elements;
 
        Splitter(string source, char[] delimiters)
        {
            // Parse the string into tokens:
            elements = source.Split(delimiters);
        }
 
        static void Main()
        {
            // Testing Tokens by breaking the string into tokens:
            Splitter f = new Splitter("This is C# Learning Lesson 8-Loops.", new char[] { ' ', '-' });
 
            foreach (string item in f)
            {
                System.Console.WriteLine(item);
            }
        }
 
    }
}

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.

using System.Collections;
 
namespace ForEachLoopApp
{
    class Splitter:IEnumerable
    {
        private string[] elements;
 
        Splitter(string source, char[] delimiters)
        {
            // Parse the string into Splitter:
            elements = source.Split(delimiters);
        }
 
        static void Main()
        {
            // Testing Tokens by breaking the string into Splitter:
            Splitter f = new Splitter("This is C# Learning Lesson 8-Loops.", new char[] { ' ', '-' });
 
            foreach (string item in f)
            {
                System.Console.WriteLine(item);
            }
            System.Console.ReadLine();
        }
 
 
        #region IEnumerable Members
 
        public IEnumerator GetEnumerator()
        {
            return new SplitterEnumerator(this);
        }
 
        #endregion
        // Inner class implements IEnumerator interface:
        private class SplitterEnumerator : IEnumerator
        {
            private int position = -1;
            private Splitter t;
 
            public SplitterEnumerator(Splitter t)
            {
                this.t = t;
            }
 
            #region IEnumerator Members
 
            public object Current
            {
                get
                {
                    return t.elements[position];
                }
            }
 
            public bool MoveNext()
            {
                if (position < t.elements.Length - 1)
                {
                    position++;
                    return true;
                }
                else
                {
                    return false;
                }
            }
 
            public void Reset()
            {
                position = -1;
            }
 
            #endregion
        }
    }
}

Output[edit]

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[edit]

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

Practice Exercises[edit]

  • 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.

References[edit]

  1. For vs Foreach Performance

-- Pasaban 08:00, 4 January 2010 (UTC)

Where To Go Next[edit]

Topics in C#
Beginners Intermediate Advanced
Part of the School of Computer Science