Saturday 4 April 2020

Break Statement in C++


Break Statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite loop, or to force it to end before its natural end. For example, we are going to stop the count down before it naturally finishes (an engine failure maybe):

// break loop example

#include <iostream.h>
int main ()
{
  int n;
  for (n=10; n>0; n--) {
    cout << n << ", ";
    if (n==3)
    {
      cout << "countdown aborted!";
      break;
    }
  }
  return 0;
}

Output
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted! 

No comments:

Post a Comment