C# Keywords Tutorial Part 18: continue

C# Keywords Tutorial Part 18: continue

Web creation, desktop and mobile application development, game development, and other fields all use the potent programming language C#. The “continue” keyword, one of C#’s many characteristics, can be used in loops to skip over some iterations and move on to the next one.

When utilizing a “for” loop, “while” loop, or “do-while” loop, the term “continue” can be used. The “continue” keyword in each of these loops will cause the loop to skip the current iteration and progress on to the following one. When some iterations are unnecessary or ought to be omitted for some reason, this can be helpful.

Here is an illustration of how to use “continue” in a “for” loop:

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0)
    {
        continue; // skip over even numbers
    }
    Console.WriteLine(i);
}

In this example, the loop starts at 1 and goes up to 10. However, if the current value of “i” is even (i.e., the remainder of “i” divided by 2 is 0), the loop will skip over that iteration and move on to the next one. This means that only odd numbers will be printed to the console.

The “continue” keyword can also be used in a “while” loop or a “do-while” loop. Here’s an example of using the “continue” keyword in a “while” loop:

int i = 0;
while (i < 10)
{
    i++;
    if (i % 2 == 0)
    {
        continue; // skip over even numbers
    }
    Console.WriteLine(i);
}

In this example, the loop starts with “i” equal to 0 and continues until “i” is less than 10. Again, if the current value of “i” is even, the loop will skip over that iteration and move on to the next one.

Finally, here’s an example of using the “continue” keyword in a “do-while” loop:

int i = 0;
do
{
    i++;
    if (i % 2 == 0)
    {
        continue; // skip over even numbers
    }
    Console.WriteLine(i);
} while (i < 10);

In this example, the loop starts with “i” equal to 0 and continues until “i” is less than 10. The difference between a “do-while” loop and a “while” loop is that a “do-while” loop will always execute at least once, even if the condition is false. In this case, the loop will continue until “i” is less than 10, and again, any even numbers will be skipped over.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *