Wednesday, December 16, 2015

break and continue

When you press "q", you can exit the infinite loop in this code:

using System;

class test
{
        static void Main(string[] args)
        {
                char myKey;
                for ( ; ; )
                {
                    // Read one character
                    myKey = (char) Console.Read();
                    if (myKey == 'q') break;
                }
        }
}


"continue" is used inside a loop to skip certain steps as follows:
using System;

class test
    {
        static void Main(string[] args)
        {
            int i = 1, n, sum;

            sum = 0;

            while (i <= 2) {
                n = int.Parse(Console.ReadLine());
                if (n < 0)
                continue;  //If n is less than 0, exit from loop
          
                sum = sum + n;
                i++;
            }
      
            Console.WriteLine("sum = " + sum);
            Console.ReadKey();
        }
    }