C Sharp

The continue Statement

Like the break statement, the continue statement enables you to alter the execution of a loop. However, instead of ending the current loop's embedded statement, the continue statement stops the current iteration and returns control back to the top of the loop for the next iteration. In the following example, I have an array of strings that I want to check for duplicates. One way to accomplish that is to iterate through the array with a nested loop, comparing one element against the other. However, I certainly don't want to compare an element to itself or I'll register an invalid number of duplicates. Therefore, if one index into the array (i) is the same as the other index into the array (j), it means that I have the same element and don't want to compare those two. In that case, I use the continue statement to discontinue the current iteration and pass control back to the top of the loop.

using System;
using System.Collections;
class MyArray
{
    public ArrayList words;
    public MyArray()
    {
        words = new ArrayList();
        words.Add("foo");
        words.Add("bar");
        words.Add("baz");
        words.Add("bar");
        words.Add("ba");
        words.Add("foo");
    }
}
class ContinueApp
{
    public static void Main()
    {
        MyArray myArray = new MyArray();
        ArrayList dupes = new ArrayList();
        Console.WriteLine("Processing array...");
        for (int i = 0; i < myArray.words.Count; i++)
        {
            for (int j = 0; j < myArray.words.Count; j++)
            {
                if (i == j) continue;
                if (myArray.words[i] == myArray.words[j]
                    && !dupes.Contains(j))
                {
                    dupes.Add(i);
                    Console.WriteLine("'{0}' appears on lines {1} and {2}",
                        myArray.words[i],
                        i + 1,
                        j + 1);
                }
            }
        }
        Console.WriteLine("There were {0} duplicates found",
            ((dupes.Count > 0) ? dupes.Count.ToString() : "no"));
    }
}

Notice that I could have used a foreach loop to iterate through the array. However, in this particular case, I wanted to keep track of which element I was on, so using a for loop was the best way.