Monday, July 2, 2018

C – continue statement

The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.

C – Continue statement

Syntax:

jump-statement;

continue;

Flow diagram of continue statement

C continue statement

Example: continue statement inside for loop





#include <stdio.h>
int main()
{
for (int j=0; j<=8; j++)
{
if (j==4)
{
/* The continue statement is encountered when
* the value of j is equal to 4.
*/
continue;
}

/* This print statement would not execute for the
* loop iteration where j ==4 because in that case
* this statement would be skipped.
*/
printf("%d ", j);
}
return 0;
}



Output:

0 1 2 3 5 6 7 8

Example of continue statement in c





#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}
return 0;
}



Output


1
2
3
4
6
7
8
9
10

As you can see, 5 is not printed on the console because loop is continued at i==5.

Value 4 is missing in the output, why? When the value of variable j is 4, the program encountered a continue statement, which makes the control to jump at the beginning of the for loop for next iteration, skipping the statements for current iteration (that’s the reason printf didn’t execute when j is equal to 4).

Example: Use of continue in While loop

In this example we are using continue inside while loop. When using while or do-while loop you need to place an increment or decrement statement just above the continue so that the counter value is changed for the next iteration. For example, if we do not place counter– statement in the body of “if” then the value of counter would remain 7 indefinitely.





#include <stdio.h>
int main()
{
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
return 0;
}



Output:

10 9 8 6 5 4 3 2 1 0

The print statement is skipped when counter value was 7.

Another Example of continue in do-While loop





#include <stdio.h>
int main()
{
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
printf("%d ", j);
j++;
}while(j<10);
return 0;
}



Output:

0 1 2 3 4 5 6 8 9

C continue statement with inner loop

In such case, C continue statement continues only inner loop, but not outer loop.





#include<stdio.h>
int main(){
int i=1,j=1;//initializing a local variable
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
if(i==2 && j==2){
continue;//will continue loop of j only
}
printf("%d %d\n",i,j);
}
}//end of for loop
return 0;
}



Output


1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.




Instagram



No comments:

Post a Comment