Skip to content
Related Articles

Related Articles

For Versus While
  • Difficulty Level : Easy
  • Last Updated : 28 May, 2017
GeeksforGeeks - Summer Carnival Banner

Question: Is there any example for which the following two loops will not work same way?




/*Program 1 --> For loop*/
for (<init-stmnt>; <boolean-expr>; <incr-stmnt>) 
{
   <body-statements>
}
  
/*Program 2 --> While loop*/
<init-stmnt>;
while (<boolean-expr>) 
{
   <body-statements>
   <incr-stmnt>
}

Solution:
If the body-statements contains continue, then the two programs will work in different ways

See the below examples: Program 1 will print “loop” 3 times but Program 2 will go in an infinite loop.

Example for program 1




int main()
{
  int i = 0;
  for(i = 0; i < 3; i++)
  {
    printf("loop ");
    continue;
  
  getchar();
  return 0;
}



Example for program 2




int main()
{
  int i = 0;
  while(i < 3)
  {
    printf("loop"); /* printed infinite times */
    continue;
    i++; /*This statement is never executed*/
  
  getchar();
  return 0;
}



Please write comments if you want to add more solutions for the above question.

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.



My Personal Notes arrow_drop_up
Recommended Articles
Page :