top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C/C++: what is the difference between for loop and while loop except its syntax?

+1 vote
158 views
C/C++: what is the difference between for loop and while loop except its syntax?
posted Sep 1, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

The main difference between while() and for() loop is when you use continue with them.
If continue is used before the increment of a variable is done it converts while() loop into a infinite loop.

Lets see an example.

i=1;
while(i < 10) {
     /* statements */
     if(i == 5);
         continue;
     i++;
}
//The above piece of code will turn into an infinite loop.

for(i = 1;  i < 10;  i++) {
      /* statements */
      if(i == 5);
          continue;
}
//Here in for loop the value of will be incremented once it attains the value of 5.
//Therefore it will not turn into a infinite loop. 

Beside those differences, you can use for() loop as a while() loop.

for(  ; condition;   )  /* exactly same as */
while(condition)
answer Sep 1, 2014 by Arshad Khan
0 votes

We normally use "for" when there is a known number of iterations and use "while" when number of iterations in not known before hand.

answer Jul 12, 2017 by Rohini Dv
...