How to control for loop using break and continue statements in C#?

CsharpProgrammingServer Side Programming

Break statement terminates the loop. To use it in a for loop, you can get input from user everytime and display the output when user enters a negative number. The output gets displayed then and exited using the break statement −

for(i=1; i <= 10; ++i) {
   myVal = Console.Read();
   val = Convert.ToInt32(myVal);


   // loop terminates if the number is negative
   if(val < 0) {
      break;
   }

   sum += val;
}

In the same way, continue statement in a for loop works, but it will not display the negative numbers. The continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating −

for(i=1; i <= 10; ++i) {
   myVal = Console.Read();
   val = Convert.ToInt32(myVal);
   // loop terminates if the number is negative and goes to next iteration
   if(val < 0) {
      continue;
   }
   sum += val;
}
raja
Published on 10-Aug-2018 10:33:33
Advertisements