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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


13


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