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

for(i=0;i<100;i++)
{
 if(i%2==0)
 {
  printf("\nI want to stop the loop");
[B]  // what to do i put in here ?[/B]
 }
}

Recommended Answers

All 5 Replies

break and continue work for any loop.

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++)
{if(i%3==0)
 {printf("stop the loop");
  j=0;
 }
}

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

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 ");
   
       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");

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.