C

C – Continue With An Example Of A Statement

Inside loops, the continue statement is used. When a continue statement is encountered within a loop, control is returned to the beginning of the loop for the next iteration, skipping the execution of statements within the loop’s body for the current iteration.

C – Continue statement

Syntax:

Continue statement inside for loop, for example

#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

Why is value 4 missing from the output? When the variable j is equal to 4, the program encounters a continue statement, which causes the control to jump to the beginning of the for loop for the next iteration, skipping the statements for the current iteration (this is why printf did not execute when j is equal to 4).

Use of continue in a While loop as an example

In this example, we use continue within a while loop. When using a while or do-while loop, add an increment or decrement statement just above the continue statement to change the counter value for the next iteration. For example, if the counter-statement is not included in the body of the “if,” the value of counter will 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

Another example of a do-while loop continue

#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

Related Articles

Leave a Reply

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

Back to top button