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


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;
}

Updated on: 20-Jun-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements