Loops Control Statements

Loops Control Statements
It is a short article on the control statements that can be used with loops. Basically there are two keywords that can be used with loops for special behavior. Those are following
  1. Break statement
  2. Continue statement
Break Statement
We already used break statement within switch statement to finish one case. It behaves similarly in loops. We can use break keyword in loop at any point to instantly finish off the loop and jump out of it. All the code after break statement will not execute.

Coding Example
    class Program
    {
        static void Main(string[] args)
        {
            int num = 10;
            while ( num < 100) {
                if (num == 60)
                {
                    break;
                }
                Console.WriteLine("The value of num is = {0}", num);
                num += 10;
            }
            Console.ReadLine();
        }
    }
Output

In above example the loop will terminate after the value of num reaches 60 because that is where if conditions executes and break statement will be performed which will cause the code to jump out of loop. While condition is still true but due to break statement the loop terminates.

Continue Statement
“Continue” is a keyword that can only be used within loops. This keyword causes the loop to skip all its remaining code for current iteration and move to next iteration. This keyword don’t terminate the loop it only skip the current iteration.

Coding example
Coding example

    class Program
    {
        static void Main(string[] args)
        {
            int num = 10;
            while ( num < 100) {
                if (num == 60)
                {
                    num += 10;
                    continue;
                }
                Console.WriteLine("The value of num is = {0}", num);
                num += 10;
            }
            Console.ReadLine();
        }
    }
Output

In this example you can see that for num = 60 the continue keyword will be executed which will cause the loop to skip the current iteration and move to next iteration due to which the 60 value is not printed.

Hope this article is helpful to you. If you have any question or suggestion, feel free to comment. Thanks.

<< Loop types and their usage
Tags: C-sharp
comments powered by Disqus