Monday 13 January 2014

csharp dotnet break keyword example

C# .net Program Break Keyword Example

  • This C# .net Program is about use Break Keyword.
  • Break Keyword is used to break the flow of program and throw the control outside the loop or conditional statement.
  • Break keyword will bring the control out of current loop in which it is written not out of all the loops.
  • Break Keyword in c# can be used with
  • For Loop
  • Swith Case
  • While Loop
  • Do While Loop
  • If Condition
  • If Else Condition

C# Program Logic:

  • In below c# program we have used while loop to show use of break keyword
  • The initial condition of while loop is set to true
  • The integer variable num is initially set to zero and incremented by 1 inside the while loop
  • Inside the while loop we have used if condition to check when the break statement should be executed.
  • In this program when the num variable is equals to 5 then the break statement is executed and controls comes out of while loop

Break Keyword C# Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BreakProgram
{
    class Program
    {
        static void Main()
        {
            int num = 0;
            while (true)
            {
                //Increment the number by 1
                num++;
                Console.WriteLine(num);
                //if num is 5 , break the loop
                if (num == 5)
                {
                    Console.WriteLine("Break Statement Executed.");
                    break;
                }
            }
            Console.WriteLine("Program End.");
            Console.ReadLine();
        }

    }
}

Output of Break Program

1
2
3
4
5
Break Statement Executed.
Program End.

No comments:

Post a Comment