The Wayback Machine - https://web.archive.org/web/20230512155149/https://www.geeksforgeeks.org/for-versus-while/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

For Versus While

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

C




/*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: using “for” loop
Syntax:

    for(initialization ; condition ; increment/decrement)
    {  
        //statement 
    }      

C




#include <stdio.h>
 
int main()
{
    int  sum=0, i;
    for(i=1;i<=5;i++)
    {
        sum=sum+i;
    }
     
      printf("SUM = %d" , sum);
     
      return 0;
}

Output

SUM = 15

Example: using the “while” loop
Syntax: 

    while(condition)
    {  
        //code for execution
    }

C




// Example:
 
#include<stdio.h>
 
int main()
{
    int no=1, sum=0;
   
    while(no<=5)
    {
        sum=sum+no;
        no++;
    }
         
      printf("SUM = %d" , sum);
 
      return 0;
}

Output

SUM = 15

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


My Personal Notes arrow_drop_up
Last Updated : 17 Jun, 2022
Like Article
Save Article
Similar Reads