C++

Providing An Example, A Continue Statement In C++

Loops contain continue statements. When a continue statement appears inside a loop, control immediately goes to the beginning of the loop for the following iteration, skipping the execution of statements inside the body of the loop for the current iteration.

Syntax of continue statement

continue;

A continue statement inside a for loop, for instance.

Although the output is missing the value 3, the for loop iterates over the num values 0 to 6, as can be seen. This is due to the fact that the continue statement is only encountered when the num value is equal to 3 thanks to a condition we specified inside the loop. In order to begin the next iteration of the loop, the loop bypassed the cout command for this iteration.

#include <iostream>
using namespace std;
int main(){
   for (int num=0; num<=6; num++) {
      /* This means that when the value of
       * num is equal to 3 this continue statement
       * would be encountered, which would make the
       * control to jump to the beginning of loop for
       * next iteration, skipping the current iteration
       */ 
     
      if (num==3) {
          continue;
      }
      cout<<num<<" ";
   }
   return 0;
}

Output:

0 1 2 4 5 6

Example: Continuation in a While loop

#include <iostream>
using namespace std;
int main(){
   int j=6;
   while (j >=0) {
      if (j==4) {
         j--;
         continue;
      }
      cout<<"Value of j: "<<j<<endl;
      j--;
   }
   return 0;
}

Output:

Value of j: 6
Value of j: 5
Value of j: 3
Value of j: 2
Value of j: 1
Value of j: 0

Continuation in a Do-While Loop Example

#include <iostream>
using namespace std;
int main(){
   int j=4;
   do {
      if (j==7) {
         j++;
         continue;
      }
      cout<<"j is: "<<j<<endl;
      j++;
   }while(j<10);
   return 0;
}

Output:

j is: 4
j is: 5
j is: 6
j is: 8
j is: 9

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button