In C language, the continue statement is used to bring the program control to the beginning of the loop. The continue statement skips some lines of code inside the loop and continues with the next iteration. It is mainly used for a condition so that we can skip some code for a particular condition.
- Flow chart of continue statement
- Example 1: Using Continue with While loop
- Example 2: Using Continue with do...while loop
- Example 3: Using Continue with for loop
- Read more about
Quick links:
Syntax: Continue statement
//loop statements
continue;
//some lines of the code which is to be skipped
Flow chart of continue statement:
Let's have a look at the below diagram how the continue statement works by using while, do...while and for loop.
continue statement | welcome2protec.com |
Example 1: Using Continue with While loop:
In below 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 (i) 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 5 indefinitely.
Let's have a look at below example:
#include <stdio.h>
int main()
{
int i=0; //initializing of counter variable
while(i <= 10)
{
if(i == 5 || i == 9)
{
printf("Skipped Value = %d\n ", i);
i++;
continue; // It will skip the value 5 and 9, when if condition returns true
}
printf("Value = %d\n ", i);
i++;
}
return 0;
}// End of loop
Output:
Value = 0
Value = 1
Value = 2
Value = 3
Value = 4
Skipped Value = 5
Value = 6
Value = 7
Value = 8
Skipped Value = 9
Value =10
Example 2: Using Continue with do...while loop
#include <stdio.h>
int main()
{
int a = 10; //initializing of counter variable
do
{
if(a == 15)
{
printf("Skipped Value = %d\n ", a);
a++;
continue; // It will skip the value 15 , when if condition returns true
}
printf("Value = %d\n ", a);
a++;
} while(a < 20);
return 0;
}
Output
Value = 10
Value = 11
Value = 12
Value = 13
Value = 14
Skipped Value = 15
Value = 16
Value = 17
Value = 18
Value = 19
Value = 20
Example 3: Using Continue with 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
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).
- go to statement
- break statement
- switch-case statement
- Control statement
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.