C++Builder Learn To Use Break And Continue In Loops With C++

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Learn To Use Break And Continue In Loops With C++
By Yilmaz Yoru April 10, 2021

1. Using break in Loops

break statement is used to break code-block in case statements and it is also used to jump out of a loop. In an earlier post, we used break in switch() statements.

For example we can break for() loops, in this loop below we can break in some step before counting all range:
C++:
for( int a=0; a<=10; a++)
{
    std::cout << a << ",";
    if(a>=5) break;
}
Here output will be 0,1,2,3,4,

we can break while() loops too like this:
C++:
int a=0;
while ( a<10 )
{
   a++;
   if( a>=5 ) break;
}
or as in same example, we can break in do-while loops:
C++:
int a=0;
do
{
   a++;
   if ( a>=5 ) break;
}while ( a<10 );

2. Using Continue in Loops

The continue statement allows you to skip next lines of block code in loops, in another way it breaks one iteration in the loop. If there is specified if-condition in that break, it will continue breaking statements while the condition is maintained.

This example below, will skip printing out 5:
C++:
for ( int a=0; a<=10; a++)
{
  if (a == 5)  continue;
  std::cout << a << ",";
}
We can use both continue and break
C++:
int a=0;
do
{
   a++;
   if ( a>=7 ) break;
   else if (a==5) continue;
   std::cout << a << ",";
}while ( a<10 );