Some times we need to exit out of the loop with out performing next iteration. SO in such case we make use of break and continue statements.

Break statement:

  1. break statement is used in order to exit from the loop.
  2. It Terminates a statement sequence in a switch statement.
Continue statement:
  1. Used to skip all the subsequent instructions and shift the cursor position back to the loop.
  2. Here the compiler tries to iterate the loop when ever the condition is satisfied .
Example:
/*....................... sum of +ve numbers..........................*/
using System;

class Break_Continue
{
static void Main(string [] arg)
{
int num,sum,i;
for(sum=num=i=0;i<5;i++)
{
Console.WriteLine("Enter the +ve number:\t");
num=Convert.ToInt32(Console.ReadLine());

if(num<=0) //............checks for +ve numbers.
continue;
sum=sum+num; //..............adds only +ve numbers.
}
Console.WriteLine("The sum of +ve numbers:\t"+sum); //..... Displays result of +ve numbers.
}
}

0 Comments:

Post a Comment



Newer Post Older Post Home