C Programming Tutorial
Computer Tutorial

The break Statement



The break Statement

We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test. The keyword break allows us to do this. When break is encountered inside any loop, control automatically passes to the first statement after the loop. A break is usually associated with an if.

a break may be used to terminate the execution of a switch, while, do-while, or for. It is important to realise that a break will only branch out of an inner-most enclosing block, and transfers program-flow to the first statement following the block.

General form of beark statement is

while ( expression  )
{

while ( expression  )
{

if ( expression  )
break ;
statements ;

}
statements ;

}

\* C Program to show the use of break statement *\
# include < stdio.h >
int   main( )
{

int   num, i  ;
printf(" Enter a number : ") ;
scanf("%d ", & num) ;
i = 2 ;
while ( i <= num - 1  )
{

if ( num % i == 0  )
{

printf(" Not a prime number ") ;
break ;

}
i++ ;

}
if ( i == num  )
printf(" Prime number ") ;
return ( 0 );

}

The continue Statement

In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed. The keyword continue allows us to do this. When continue is encountered inside any loop, control automatically passes to the beginning of the loop.

The continue-statement operates on loops only; it does not operate on switch. For while and do-while it causes transfer of program-control immediately to the conditional test, which is reevaluated for the next iteration. The same action occurs for a for-loop after first executing the increment expression .

General form of beark-continue statement is :

while ( expression  )
{

statements ;
if ( expression  )
{

statements ;
if ( expression  )
break ;
statements ;

}
statements alter if

}
statements after loop

\* C Program to show the use of continue statement *\

# include < stdio.h > int   main( )
{

int   i, j  ;
for ( i = 1 ; i <= 2 ; i++  )
{

for ( j = 1 ; j <= 2 ; j++  )
{

if ( i == j  )
continue ; printf("\n %d %d \n ", i, j) ;

}

}
return ( 0 );

}