Get up to 60 % extra points for free! More info
Save up to 80 % on our Python e-learning courses. Only this week!

Lesson 12 - More on C# loops

In the last lesson, More on C# conditions, we focused on another syntax of conditions.

At the beginning, it'd be good to note that today's lesson contains less used practices and is mainly used to prevent you from being surprised when you see them in foreign code. It isn't very important that you know how to use them yourself.

do...while

We already know the while loop well. Less used do...while differs only in that it's always executed at least once. Its condition is located after the loop's body. So it looks like this:

do
{
    // code...
} while (condition)

We can also use a snippet in Visual Studio to write this loop: We'll write do and double-press Tabulator. The rest of the loop will be written itself.

Example

Let's use the do-while loop in our calculator from the lesson about loops. We won't use the version with "user input verification" to shorten the example.

Variant with while

We used while in the calculator, which allowed us to repeat the whole program and thus enter more and more numbers. The code looked like this (this is the version with the switch construct):

Console.WriteLine("Welcome to the calculator");
string continue = "Yes";
while (continue == "Yes")
{
    Console.WriteLine("Enter the first number:");
    float a = float.Parse(Console.ReadLine());
    Console.WriteLine("Enter the second number:");
    float b = float.Parse(Console.ReadLine());
    Console.WriteLine("Choose operation:");
    Console.WriteLine("1 - addition");
    Console.WriteLine("2 - subtraction");
    Console.WriteLine("3 - multiplication");
    Console.WriteLine("4 - division");
    int choice = int.Parse(Console.ReadLine());
    float result = 0;
    switch (choice)
    {
        case 1:
            result = a + b;
            break;
        case 2:
            result = a - b;
            break;
        case 3:
            result = a * b;
            break;
        case 4:
            result = a / b;
            break;
    }
    if ((result > 0) && (choice < 5))
        Console.WriteLine("Result: {0}", result);
    else
        Console.WriteLine("Invalid selection");
    Console.WriteLine("Do you want to enter another example? [Yes/No]");
    continue = Console.ReadLine();
}
Console.WriteLine("Thank you for using the calculator, you can close the application with any key.");
Console.ReadKey();

Note that in this variant with while we had to think about the continue variable's default value, which we set to "yes" so that the condition is met for the first pass of the loop. However, introducing a default value can sometimes be quite complicated and may require an auxiliary variable.

Variant with do-while

When we use do-while, we don't have to worry about a default value of the given variable:

Console.WriteLine("Welcome to the calculator");
string continue;
do
{
    Console.WriteLine("Enter the first number:");
    float a = float.Parse(Console.ReadLine());
    Console.WriteLine("Enter the second number:");
    float b = float.Parse(Console.ReadLine());
    Console.WriteLine("Choose operation:");
    Console.WriteLine("1 - addition");
    Console.WriteLine("2 - subtraction");
    Console.WriteLine("3 - multiplication");
    Console.WriteLine("4 - division");
    int choice = int.Parse(Console.ReadLine());
    float result = 0;
    switch (choice)
    {
        case 1:
            result = a + b;
            break;
        case 2:
            result = a - b;
            break;
        case 3:
            result = a * b;
            break;
        case 4:
            result = a / b;
            break;
    }
    if ((choice > 0) && (choice < 5))
        Console.WriteLine("Result: {0}", result);
    else
        Console.WriteLine("Invalid selection");
    Console.WriteLine("Do you want to enter another example? [Yes/No]");
    continue = Console.ReadLine();
} while (continue == "Yes");

Console.WriteLine("Thank you for using the calculator, you can close the application with any key.");
Console.ReadKey();

break and continue

It's sometimes necessary to interrupt the loop's run, for this we have two following keywords.

break

The break keyword terminates the current loop. It's most often used when we use the loop to find an item in the collection and don't want to continue browsing it. We'll no longer keep searching the rest of the collection unnecessarily, when we already have what we're looking for.

Example

Let's say we have an array of items and we want to find one in them. Maybe you say we can use the IndexOf() or the Contains() method? If it's an array, yes, but some collections don't have it and/or we want to search for it by some other property than these methods take into account. Then we have to implement the searching manually using a loop or using significantly more advanced constructs than we now know.

Imagine that we have large and small tags for jars and we want to use one or the other for all jars. So we're interested in whether all the texts will fit on small tags. We'll write a program that will find out if there is a word longer than 6 characters in an array. If so, we need to use larger tags.

We start going through individual words with a loop and as soon as we find a word longer than 6 characters. Then we'll store its index. Still nothing new. At the same time, however, we'll end the loop with break.

The example of using break:

string[] fruitsList = {"Apples", "Pears", "Plums", "Apricots", "Strawberries", "Cherries"};
int searchedIndex = -1;

for (int i = 0; i < fruitsList.Length; i++)
{
    if (fruitsList[i].Length > 6)
    {
        searchedIndex = i;
        break;
    }
}

if (searchedIndex >= 0)
    Console.WriteLine("First word longer than 6 characters: " + fruitsList[searchedIndex]);

Output:

Console application
First word longer than 6 characters: Apricots

In practice, break is often replaced by return, assuming that the code is in our own method. However, we'll learn to declare our own methods in the following course Basics of Object-Oriented Programming in C#. Then I recommend not to use break, the more correct variant is to move the code for working with the collection into a separate function.

continue

The continue keyword is similar to break. However, it's used to terminate only the current iteration of the loop and not the entire loop. The loop then goes straight to the next iteration. We can encounter continue, for example, when validating items while browsing a collection.

Example

Let's say the user enters few numbers and we want to add up these numbers. The user enters the numbers as a single string, where each number is separated by a comma. Unfortunately, we must also expect a fact that the user enters some nonsense instead of a number. The solution could look like this:

string stringNumbers = "10,50,abcd,30,9";
// splitting a string into an array
string[] arrayNumbers = stringNumbers.Split(',');
int sum = 0;
foreach (string number in arrayNumbers)
{
    // converting a string to an integer
    int integer;

    if(!int.TryParse(number, out integer))
        continue;

    sum += integer;
}
Console.WriteLine("The sum is: " + sum);

Output:

Console application
The sum is: 99

The program sums all correctly entered values, i.e. those for which the TryParse() method returned true. For incorrectly entered values, the current iteration is terminated. Of course, we could just use if instead of continue, but we'd overwhelm the code unnecessarily.

Abbreviated syntax of the for loop

The following constructs are here just to show what can be found in foreign code and there's no good reason to use them!

The for loop can be abbreviated as follows, without the body of the loop:

for (int i = 0; i < 10; Console.Write(i++));

Output:

Console application
0123456789

However, it isn't intuitive to write the logic of the loop's run and the logic of the loop on a single line. In addition, we can easily forget to increment the variable or we increment it multiple times.

It isn't even necessary to specify any command in the for loop:

for (;;)
{
    // endless loop
}

This is the same as follows:

while (true)
{
    // endless loop
}

Both of the loops declared above run indefinitely, and you may encounter them in badly written source code, along with break statements, which then pop out under certain conditions.

Once a condition isn't directly in the loop's declaration, it's relatively confusing to find out when the loop ends at all, and easy to make such a loop infinite by mistake. This is especially true when there are more conditions in the loop and we don't cover all possible cases.

Although today's lesson included a standard C# .NET grammar for loops, of the new constructs, use only do-while and continue. You can temporarily use break before we get to the objects :)


 

Previous article
More on C# conditions
All articles in this section
C# .NET Basic Constructs
Article has been written for you by Radek Vymetalik
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Activities (4)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!