Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Loops

Loops are a fundamental component of every modern programming language. Whenever a set of commands has to be executed more than once, a loop is a good idea and, in many cases, the only choice.

C# provides all fundamental kinds of loops and we take a closer look at them in this section.

while

while loops are a widespread way to perform repeated computation. A while loop is executed as long as a certain condition returns true. The next listing contains a program showing how things work:

using System;

class  Loop
{
    public static void Main()
    {
        bool keepdoing = true;
        string input;

        while  (keepdoing == true)
        {
            Console.Write("Input: ");
            input = Console.ReadLine();
            Console.WriteLine("Output: " + input);

            if   (input.Length < 3)
                keepdoing = false;
        }
    }
}

As an alternative to keepdoing == true, we could have used while (keepdoing). The target of the program is to accept input as long as the user inserts data that's longer than two characters. Therefore, we create two variables. The first one is a flag telling us whether the loop is supposed to keep going. The second variable contains the string provided by the user. The loop is executed as long as keepdoing is true. After the user has entered the new record via his keyboard, we compute the length of the string. If it's too short, we set the flag and the loop terminates. The length of a string can be retrieved using the Length method. This method is part of the class called String—we'll deal with this class extensively later in the book.

The next listing shows what might happen:

[hs@duron mono]$ mono while.exe
Input: I am inside
Output: I am inside
Input: a loop.
Output: a loop.
Input: It is fun to be here.
Output: It is fun to be here.
Input:
Output:

After the third input, the program terminates.

When talking about loops, the keyword continue is important. It makes sure that a program can jump directly to the condition of a loop. This feature is nice to have, particularly when implementing blocks that consist of many lines.

do/while

When a loop must be executed at least once, an ordinary while loop just isn't what you're looking for. A do/while loop is easier to implement and is more suitable for this special purpose. The following listing contains a brief example showing the way do/while loops can be used:

using System;

class  Loop
{
    public static void Main()
    {
        bool again = true;
        string input;

        do
        {
            Console.WriteLine("Y: yes");
            Console.WriteLine("N: no");
            Console.Write("Input: ");

            input = Console.ReadLine();
            Console.WriteLine("Output: " + input);

            if   (input == "N")
                again = false;
        } while    (again == true);
    }
}

The program displays an interactive menu and checks whether the loop should be processed again. As long as the user doesn't enter N, the program keeps asking for input. It's important to mention that the process is case sensitive, so entering n does not terminate the program:

[hs@duron mono]$ mono loop.exe
Y: yes
N: no
Input: Y
Output: Y
Y: yes
N: no
Input: Y
Output: Y
Y: yes
N: no
Input: n
Output: n
Y: yes
N: no
Input: N
Output: N

do/while loops are normally used to perform far more complex operations. In this book, we try to focus on the most basic and most important facts so that you can get in touch with Mono and C# quickly.

for Loops

for loops are an important alternative to while loops. In principle, every operation you can implement with the help of a while loop can be implemented based on a for loop as well. It depends on which loop the programmer likes best and which method is best to achieve a certain target.

In this section, we take a closer look at for loops. Again, let's start with a simple example:

using System;

class  MyLoop
{
    public static void Main()
    {
        int i;
        for   (i = 0; i < 6; i++)
        {
            Console.WriteLine("current value: " + i);
        }
    }
}

Before we get to the loop, we define a variable called i. Inside the loop, we've defined that the first value of i should be 0. Every time the block is executed, i is incremented. Therefore, we use i++. The ++ operator is widespread because it's efficient and many C/C++ programmers are already familiar with this feature. The loop is executed as long as i is less than a specific value. In our case, this value is 6. In this example, we used parentheses around the block we want to execute. This isn't a must, but it makes sure that the program is easier to read and therefore easier to understand. i++ is the same as i = i + 1. The counterpart of i++ is i--. i-- means that i is decremented.

Let's see which result we can expect:

[hs@duron mono]$ mono forloop.exe
current value: 0
current value: 1
current value: 2
current value: 3
current value: 4
current value: 5

As you can see in the listing, all numbers from 0 to 5 are displayed.

The same target can be achieved with the next piece of code:

using System;

class  MyLoop
{
    public static void Main()
    {
        int i;
        for   (i = 0; i < 6; )
        {
            Console.WriteLine("current value: " + i);
            i++;
        }
    }
}

In this example, we omitted the third argument of the function. Whenever a loop is more complex, this can be essential because the current value of the parameter (in our case, i) might be the result of complex operations. In the example, we've incremented i inside the loop. The result is the same.

  • + Share This
  • 🔖 Save To Your Account