Skip to content
Related Articles

Related Articles

Improve Article

For Versus While

  • Difficulty Level : Easy
  • Last Updated : 28 May, 2017

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

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.




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




My Personal Notes arrow_drop_up
Recommended Articles
Page :