Guys, can u tell me a good programming practice to stop iteration inside a for loop based on a condition, that is, something equivalent to a break in a while loop

suppose i am iterating inside a for loop, looking for the first number divisible by 2,
i would do

  printf("\nI want to stop the loop");
[B]  // what to do i put in here ?[/B]

To expand on what has been said you can use break to break out of the loop and continue to skip the current execution for example :

for(int i = 0; i < 5; ++i){
  if(i == 3) break;

will break out of the loop that is exit out of the loop when i == 3 is true.

Similarly, the code:

for(int i = 0; i < 10;++i){
  if( i % 2 == 0 continue; //if i is even then skip to next iteration but does not exit out of the for loop

Hello tubby123,
Apart from break and continue you can try this one also,

int i,j=1;
for(i=1;i<=20 && j!=0;i++)
 {printf("stop the loop");

Edited 5 Years Ago by Arbus: n/a

You make "BREAK" statement.
But how can we make "CONTINUE" statement using for loop?

>>Utsav Chokshi,
Here is a block using continue...

int i;
for(i=1 ; i<=20 ;i++ )
  printf(" \n testing ");
    if( i % 3==0 )
    {  printf(" continue ");
 printf("\n hello ");


The same block without using continue...

int i , j=1;

for(i=1 ; i<=20 ; i++)
{ printf("\n testing ");
 if( i % 3==0 )             /* the statements above continue(that is from line 3 to 7 */
 {  printf("\ncontinue");

 if( j!=0 )
 {   printf(" \nhello "); /*This is where you give the statements following continue*/

Variable j is used as a counter. So if value of i is divisible by three then j becomes 0 and hello will not be printed.

Edited 5 Years Ago by Arbus: n/a

This article has been dead for over six months. Start a new discussion instead.