For Versus While

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

filter_none

edit
close

play_arrow

link
brightness_4
code

/*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>
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




Example for program 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




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

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


10


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.