Jun 27, 2014

C Programming #25: Loop - continue

This section will discuss the usage of continue in loop. The use of continue  very similar to that of break, but the outcome is totally different.

Syntax for using continue in different loops-



for(initialize_counter; condition; change_condition) {
   statement1;
   if(condition_x) {
     continue;
   }
   statement2;
}

while(condition) {
   statement1;
   if(condition_x) {
     continue;
   }
   statement2;
}

do{
   statement1;
   if(condition_x) {
     continue;
   }
   statement2;
}while(condition);

In above usages, if "condition_x" becomes true, loop "statement2" is not executed, but loop goes to next iteration, by

  • executing "change_condition" in case of for loop and
  • "condition" in case of while loop and do while loop. 
Similar to break, continue also disturbs the normal loop flow, and my suggestion is to avoid it. Lets take an example to understand the working of continue.

Program to find the sum of number between n and m which are not multiple of 3, 5 or 7.
Strategy:
We will iterate from n to m using for loop as we max loop counter. Sum will be maintained by variable s. If the number is multiple of 3, 5 or 7 then cumulative sum calculation is not done specifically.


#include <stdio.h>

int main()
{
   int n = 5, m = 30;
   int s, counter;

   s = 0;

   for(counter = n; counter <= m; counter ++) {
      if(counter % 3 == 0 || counter % 5 == 0 || counter % 7 == 0) {
         continue;
      }
      s = s + counter;
   }
   printf("Sum is %d\n", s);
   return 0;
}

Output of the above program is


Sum is 184

To prove my point earlier I will write the same program without using continue


#include <stdio.h>

int main()
{
   int n = 5, m = 30;
   int s, counter;

   s = 0;

   for(counter = n; counter <= m; counter ++) {
      if(counter % 3 != 0 && counter % 5 != 0 && counter % 7 != 0) {
         s = s + counter;
      }
   }
   printf("Sum is %d\n", s);
   return 0;
}


Links

Quiz - Not Yet written !!
Next Article - C Programming #26: Loop - nested
Previous Article - C Programming #24: Loop - break
All Articles - C Programming

No comments :

Post a Comment