C/C++: Difference between "while" loop and "for" loop ?!?

There's an interesting story behind this!

I went to an interview where the interviewer (who looked pretty knowledgable) asked me, among other things, to write a program in C++ to display the first ten prime numbers... the "first ten", mind you, not "prime numbers less than 10."

Nervous as I was (first interview, please understand!!), I set about the task by inserting a couple of "for" loops here and there... Nothing came to mind, while the interviewer sat there clicking her tongue. After about five minutes, apparently she had had enough, and proceeded to scold me, "See, that's the exact mistake your predecessor made. You should use a while loop.. a for loop won't work for you in this situation.

"What is the difference between a for loop and a while loop?", she asked. This question came as a surprise to me. I tried to avoid the question, "I know the difference between a do...while loop and a while loop." But no, she wanted to know the difference between a "while" loop and a "for" loop...

...And that's where it all ended, I suppose. She scoffed at me and whispered in an undertone, "And you got 87% in aptitude!!" (*****). Anyway, back in the comfort of my home, I wrote a perfect program for the same using >>only<< "for" loops.

And that's why I'm totally bamboozled. I'd like to think that the interviewer was off her rocker, but... "innocent until proven guilty", I suppose. I've asked all my friends the same question, and they all answered the same way I did. I've looked into many books and there's no mention of a difference between the two (on the contrary, they preach ways to convert between them, to add to my frustration!)

Hoping someone would provide me with a satisfactory answer...

Yours frustratingly,
Maelstrom

[BTW: If you don't know how to write the program yourself... DO NOT press the Reply button]

Replies

  • Manish Goyal
    Manish Goyal
    Nice question This Question was asked by my Teacher at my 6 weeks training
    According to my knowledge
    a for loop repeats for a predefined number of times

    a while loop repeats as long as a certain condition is true
    ......
  • yadavundertaker mohit
    yadavundertaker mohit
    typical question dude.......
  • yadavundertaker mohit
    yadavundertaker mohit
    ...

    The difference between the two is where the test for the condition is. For example, suppose a variable is equal to 10. This is followed by a while loop which runs so long as the variable is equal to 11.
  • Maelstrom
    Maelstrom
    Sorry guys, I still don't get the point. Maybe reframing the question would be a bit of a help...

    Let's start out with the assumption that there's no difference. Just humour me for a minute... Directly derived from this assumption is the inference that Dennis Ritchie made a stupid mistake to include both the loops in the language, since we can always use them interchangeably...

    [Sidenote: Maybe the while loop is there simply for convenience, in cases where we don't need a counter - like "while(!feof(fp))" - and the for loop is there in cases where we need a counter?? ...Maybe not. It seems a waste to me.. I mean, it's not a humongously large task to initialize a counter just before the start of the while loop and provide an increment at the end.... Why make a separate programming construct just to avoid this small thing?]

    ... Anyway, getting back to the point, what I'd like to hear is evidence on why including both the for and while loops is not just plain stupidity.

    Atleast, having the for loop makes a lot more sense in Visual Basic [especially the For Each... Next variation] in which case it provides a much bigger convenience advantage over its corresponding While... End While equivalent.

    yadavundertaker
    ...

    The difference between the two is where the test for the condition is. For example, suppose a variable is equal to 10. This is followed by a while loop which runs so long as the variable is equal to 11.
    I disagree [or maybe I just didn't understand]. Would you care to elaborate [maybe with an example?]

    Thank You.
  • Gurjeet Singh
    Gurjeet Singh
    a FOR loop is used when you know in advance that how many times you want to execute the particular block of code.
    a WHILE loop is used when in advance you do not know how many times your block of code will be executed.. eg-WHILE read records until END OF FILE
  • Manish Goyal
    Manish Goyal
    For loop can only be used for uniform iterations where as while loop can be used for non uniform iterations
  • tashirosgt
    tashirosgt
    The interviewer must have had some stereotyped answer for the program already in mind that happened to use while-loops. You don't want to work for a company that hires interviewers like that.
  • Manish Goyal
    Manish Goyal
    I thought a lot for this Question and concluded that..basically there is no difference between for loop and while loop after all both are used for carrying out iterations..
    think when bjarne stroustrup created c++..what occurs in his mind...??
    while looks better with some condition and for looks better with upto some point
    so we can say for loop is used for uniform iterations and while loop is used for non uniform iterations...
    or we can say for loop works better when we have already predefined no of iterations whereas while loop when we have given certain condition
    so here both are used for carrying out iterations only
    I hope you are satisfied with my answer
  • vik001ind
    vik001ind
    These things we don't learn, we come up with answers of such questions as per our programming skills. Some interviewers have written answers or predefined answer of such questions & they just wanna hear that only which is depressing.
    There is just structural difference between the two, where you iterate, where the condition is checked. Both of them do the same thing.
    I think while loop is more flexible in terms where we do iteration & initialization, whereas for loop give as a defined structure to do that..
    I think Students like for loop as it is easier to implement due to its structure.
  • Maelstrom
    Maelstrom
    GUYS!! I GOT IT!!!!

    If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.

    Jesus! I can't believe it was such a hidden answer like this.

    Amazing! All those books, and I thought atleast one of them would have mentioned it...
  • vik001ind
    vik001ind
    I don't think you got it right.
    That depends where you put continue statement, if you put increment variable after continue in while loop then it will loop forever, if you put increment before, it will behave normally..
    continue is just used to jump directly to the condition of loop, ignoring other statements below it..

    check it again!
  • Manish Goyal
    Manish Goyal
    Maelstrom
    GUYS!! I GOT IT!!!!

    If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.

    Jesus! I can't believe it was such a hidden answer like this.

    Amazing! All those books, and I thought atleast one of them would have mentioned it...
    can you give any code..that will illustrate it...😕?
  • safwan
    safwan
    As far as I know is for loop will automatically increment the value and will execute the block of code .but while loop requires the increment value for going next time.😀

    If you use "continue" in a "for" loop, it will still increment the variable. But if you use continue inside a "while" loop with counter, then it will turn into an infinite loop.
    your saying is right.
  • Saandeep Sreerambatla
    Saandeep Sreerambatla
    vik001ind
    I don't think you got it right.
    That depends where you put continue statement, if you put increment variable after continue in while loop then it will loop forever, if you put increment before, it will behave normally..
    continue is just used to jump directly to the condition of loop, ignoring other statements below it..

    check it again!

    This is correct!!

    Generally continue is used to skip one execution.

    Any loop can turn into infinite loop !!
  • Saandeep Sreerambatla
    Saandeep Sreerambatla
    To say one difference is For loop is a loop which executes for some predefined number of times.

    Where as the while loop executes until the given condition is true.
  • Manish Goyal
    Manish Goyal
    hey genrally i think continue usually comes with if condition..
    if i use say
    while(i!=10)
    {
    if(i==5)
    {
    continue;
    }
    else
    {
    i++;
    }
    }
    then there will be infinite loop or not
  • tashirosgt
    tashirosgt
    The code in the for-loop is executed before a test is made to see if the stopping condition is reached.

    So

    n = 6;
    j = 3;

    for(i = 0; i < 4 && n < 6; i++)
    {
    n++;
    j = 4;
    }

    Will set j equal to 4

    [ No, it won't. Malestrom corrects me later in this thread. I'm thinking of the old fashioned FORTRAN DO-loops which were executed at least once.]

    But if the code is:

    n = 6;
    j = 3;
    i = 0;
    while( i < 4 && n < 6)
    {
    i++;
    j = 4;
    }

    Then j will remain at 3
  • Maelstrom
    Maelstrom
    goyal420
    can you give any code..that will illustrate it...?
    ~ Using a for loop ~

    for(i = 0; i < 10; i++)
    {
    if(i == 5) continue;
    printf("%d ", i);
    }

    OUTPUT: 0 1 2 3 4 6 7 8 9 [notice that '5' is missing]

    ~ Using a while loop ~

    i = 0;
    while(i < 10)
    {
    if(i == 5) continue;
    printf("%d ", i);
    i++;
    }

    OUTPUT: 0 1 2 3 4 ....... [the cursor will remain there, stuck in an infinite loop]
    tashirosgt
    j = 3;
    n = 6;
    for(i = 0; i < 4 && n < 6; i++)
    {
    n++;
    j = 4;
    }

    Will set j equal to 4
    I don't think you got this right! The condition inside the for loop is "i < 4 && (LOGICAL AND) n < 6", so irrespective of the value of i, this condition will return FALSE, because n is NOT LESS THAN 6. Hence, the for loop will not execute even once, resulting in the value of j remaining at 3.
  • Manish Goyal
    Manish Goyal
    Maelstrom
    ~ Using a for loop ~

    for(i = 0; i < 10; i++)
    {
    if(i == 5) continue;
    printf("%d ", i);
    }
    OK bASIC you can say this since in for loop all the three requirements to carry out iterations comes together
    but what about this
    for(i=0;i<10; )
    {
    if(i==5)continue;
    printf("%d",i);
    i++;
    }
    I have not try this..but what do you think what will be the output?
  • Maelstrom
    Maelstrom
    goyal420
    I have not try this..but what do you think what will be the output?
    Yes, you are right, in this case it will be just like the infinite while loop.

    This leads me to believe that a for loop was made specifically for cases where the programmer wanted to ensure that the counter would be incremented after each iteration of the loop no matter what happens. [Of course, for that to happen, the programmer would have to provide the increment inside the for() statement itself.]

    Only now do I fully understand what all the others were trying to say.

    I always thought that the for loop is the looping structure used by default. However, now I come to realize that the while loop is the most general looping statement available, whereas the for loop and the do...while loop are provided for specific purposes. Of course, the 'specific' purpose of iterating for a known number of times is so common that it is not hard to see why a for loop is encountered so many more times than a while loop.

    After careful thought, I have come up with (arguably) a few "rule-of-thumb"s for programmers (it's like social rules in the world, nobody tells you this, you just know):
    1.If you want the body of the loop to execute atleast once irrespective of the condition, then use a do...while loop.
    2.If you want to use a counter to keep track of the number of iterations of the loop, use a for loop [it goes without saying that you put the increment inside the for() statement...]
    3.For all other cases, use a while loop.
    4.By default, use a while loop [Ignore this at your own peril (see the first post)]
    I cannot stress this enough. USE A WHILE LOOP. For me and programmers like me, the word "loop" is synonymous with a for loop. All I can say is, think before using the for loop from now on. If you don't need a counter, use a while loop. Especially when you are using an infinite loop like for(..) [just replace the periods with semicolon, it's showing a smiley where I don't want it to] instead use while(1).

    (Programmers with any ammount of credibility may wish to argue with me on, especially, the last point. However, I have paid my price - I merely wish no one else the same trauma.)
  • maggi.sharma
    maggi.sharma
    The main difference comes into picture when you use continue with them i.e. for and while.
    In a while loop if continue is used before the increment of a variable is done it converts into a infinite loop.
    i=1;
    while(i<10)
    {
    /* do stuff */
    if(i==6);
    continue;
    i++;
    }
    The above piece of code will turn into an infinite loop.
    for(i=1;i<10;i++)
    {
    /* do stuff */
    if(i==6);
    continue;
    }

    In the above for loop the value of will be incremented once it attains the value 6.
    Therefore it will not turn into a infinite loop.

    'for' statement takes the start condition, stop condition, and the increment. 'while' statement just takes the stop condition.


    Another main difference between the two: a 'for' loop is called a determinate loop, meaning that we usually use it when we know ahead of time how many iterations we want. The 'while' loop is an 'indeterminate' loop, because we usually use it in situations where we do not know the number of times the loop may iterate.

    HOPE IT WILL HELP.😛
  • sanjana17
    sanjana17
    The lady who took ur interview is right. look....u can use for loop to pront prime nos. LESS THAN 10!but NOT for first 10 prime nos. !!for that u have to use while loop.
  • Mayank 07
    Mayank 07
    One first basic rule is that you should use the for loop when the number of iterations is known. For instance:

    • The loop iterates over the elements of a collection.
    • The loop iterates over a range of values which is known in advance at execution time.
    • The object provides a way to iterate over its elements with a for statements (e.g files).


    The while loop is the more general one because its loop condition is more flexible and can be more complicated than that of a for loop. The condition of a for loop is always the same and implicit in the construction. A for loop stops if there are no more elements in the collection to treat. For simple traversals or iterations over index ranges it is a good advice to use the for statement because it handles the iteration variable for you, so it is more secure than while where you have to handle the end of the iteration and the change of the iteration variable by yourself.
    The while loop can take every boolean expression as condition and permits therefore more complex end conditions. It is also the better choice if the iteration variable does not change evently by the same step or if there are more than one iteration variable. Even if you can handle more than one iteration variable in a for statement, the collections from which to choose the values must have the same number of elements.Hope it's handy for u.

  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Simple Definition
    For Loop is a counter loop.
    While Loop is a conditional loop.
  • Deepika Bansal
    Deepika Bansal
    sanjana17
    The lady who took ur interview is right. look....u can use for loop to pront prime nos. LESS THAN 10!but NOT for first 10 prime nos. !!for that u have to use while loop.
    Or similarly, in place of whle loop, we can use an additional for loop that'll count the number of prime number found till time.
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Deepika Bansal
    Or similarly, in place of whle loop, we can use an additional for loop that'll count the number of prime number found till time.
    Why do you need to complicate the program when you just use a single for loop or while loop to do it?
  • Deepika Bansal
    Deepika Bansal
    Nothing like that Praveen. It is just that earlier outer 'while' loop was counting the number of prime numbers and the inner 'for' loop was finding them. I'm comfortable with 'for' loop so I proposed using outer loop as 'for' instead of 'while'. Simple.
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Deepika Bansal
    Nothing like that Praveen. It is just that earlier outer 'while' loop was counting the number of prime numbers and the inner 'for' loop was finding them. I'm comfortable with 'for' loop so I proposed using outer loop as 'for' instead of 'while'. Simple.
    Yeah, I agree, but your combination will use both the loops na?
  • Deepika Bansal
    Deepika Bansal
    Yeah. It all depends on your ease of using a loop. With some little modifications, they can be used interchangeably.
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    That's what am saying... Understand, for a simple stuff, why do you need two loops... This is my question...
  • Aman Goyal
    Aman Goyal
    can anyone plz post the program to display the first 10 prime nos,i know how to check for prime and also to print prime nos in a given range but not getting this specific problem
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Say the logic to check the prime numbers... 😀 I will try to give you a solution... 😀
  • Aman Goyal
    Aman Goyal
    cout<<"Enter the number\n";
    cin>>n;
    for(i=2;i
                                        
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    First 10 prime numbers...

    int isPrime(int n)
    {
        for (i = 2; i < n / 2; i++)
        {
            if (n % i == 0)
            {
                f = 1;
                break;
            }
        }
        return f == 1;
    }
    
    // In the main function
    
    int cnt = 0, i = 0;
    while (cnt < 10)
    {
        if(isPrime(i))
        {
            cout<Hope this helps... 😀
                                        
  • Aman Goyal
    Aman Goyal
    thnx a lot,but can it be done w/o function?
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Yes, it can be done... But if so, the whole function would be executing about a 100 times!!! Is that fine and is it not a performance issue??? 😐
  • ayusha patnaik
    ayusha patnaik
    for loop is easier than while loop cz of its structure that we write the update expression in the same line..whr as in the while loop dr is a chance of the update expression getting missd and hence creation of an infinite loop...both being loops..both can be used in programs...bt asfar as i knw..while loop makes a complicated problem get an easier program than for loop cz smtyms for loops r lengthier..apart frm that while loop nt havin any initial is more flxible and can be used in any program nd yeah it is told by teachers that sm programs cant be done by all the loops..bt i blv at a hghr level things can b done by any means jst the complicacy level matters...i think since u used for loops in an interview it wd have bn long and the interviwer lackd patience and wanted u to get finishd as soon as possible...so she flew her rage at u!
  • proveitboy
    proveitboy
    Maelstrom
    There's an interesting story behind this!

    I went to an interview where the interviewer (who looked pretty knowledgable) asked me, among other things, to write a program in C++ to display the first ten prime numbers... the "first ten", mind you, not "prime numbers less than 10."

    Nervous as I was (first interview, please understand!!), I set about the task by inserting a couple of "for" loops here and there... Nothing came to mind, while the interviewer sat there clicking her tongue. After about five minutes, apparently she had had enough, and proceeded to scold me, "See, that's the exact mistake your predecessor made. You should use a while loop.. a for loop won't work for you in this situation.

    "What is the difference between a for loop and a while loop?", she asked. This question came as a surprise to me. I tried to avoid the question, "I know the difference between a do...while loop and a while loop." But no, she wanted to know the difference between a "while" loop and a "for" loop...

    ...And that's where it all ended, I suppose. She scoffed at me and whispered in an undertone, "And you got 87% in aptitude!!" (*****). Anyway, back in the comfort of my home, I wrote a perfect program for the same using >>only<< "for" loops.

    And that's why I'm totally bamboozled. I'd like to think that the interviewer was off her rocker, but... "innocent until proven guilty", I suppose. I've asked all my friends the same question, and they all answered the same way I did. I've looked into many books and there's no mention of a difference between the two (on the contrary, they preach ways to convert between them, to add to my frustration!)

    Hoping someone would provide me with a satisfactory answer...

    Yours frustratingly,
    Maelstrom

    [BTW: If you don't know how to write the program yourself... DO NOT press the Reply button]
    The answer I would like to give is..

    In a 'for' you know what is the intial value of the iterator (say 'i')..
    Therefore, a 'for' loop is used where you know the initial value of the iterator and 'while' loop when you do not know what the initial value of the iterator is...
    This is just my way of answering your question...
    Ready to recieve comments....
  • vinci
    vinci
    hello
    First of all syntactically for loop and while loops are different.Syntax of both are different
    Second ,a for loop initiates ,check for error,and increment at the same time at once....a while doesnt do that.While loop just mark upper bound and starts looping till that higher bound
  • vinci
    vinci
    hello
    First of all syntactically for loop and while loops are different.Syntax of both are different
    Second ,a for loop initiates ,check for error,and increment at the same time at once....a while doesnt do that.While loop  just mark upper bound and starts looping till that higher bound

    also an empty while loop is not valid but empty for loop is valid
  • cilvan
    cilvan
    In the for loop,we can initialize counter,test the condition and also increment/decrement the counter variable whereas in while only the condition is written and the increment/decrement is given at the bottom.

    In for loop assignment,increment/decrement and condition checking are done in the same line which no other loop offer.Hence we can reduce the number of lines in coding.We can initialize,increment/decrement more than one variable and test condition can also have a compound relation.

    Though both loops can be used,the following strategy is usually followed:
    Choose for loop,if the programmer exactly knows how much times the loop is needed to be executed.(while can also be used)
    Choose while loop,if programmer is not sure how much times the loop need to be executed since the condition is tested for repetition.(for can also be used)
  • Smriti Jha
    Smriti Jha
    I think what she meant was a for loop would require a predefined number of iterations. Considering you don't know where the tenth prime number occurs, a while loop would be the preferred option. I am thinking a while loop and if statement would do the trick.
  • ayusha patnaik
    ayusha patnaik
    while loop may deal with infinity on the other hand for loop never deals with infinity
  • b_sothiya
    b_sothiya
    There is no difference between while and for loop.
    you can handle any problem with any loop, there is no program wich can be
    handle by for and not by while and vice-versa.
    the only difference in the application, i.e. if no. of iteration are known then using for is better
    otherwise while is better.
    give me any problem i can do with "while" and "for" with both...?
    challenge..?
  • crazy_sam
    crazy_sam
    Hi guys ,
    I am Sam and I am new to this forum and would like to be a part of this team. Please accept me as a team member so that i can share my views and get an opportunity to chat with the tech gurus here..

    I understand that there is little difference in the structure of while and for loops, but for a programmer it is a negligible issue. The while statement is generally used as a simple conditional loop. However, a for statement can also be used in place of while statements like for(;condition😉. There is nothing like a "A for loop is a counter loop " or a " while loop is a conditional loop" as per my knowledge. It depends on the way u use it . Generally because of the ease in use people use ,for loop as it initializes itself in the structure so they use it as counter loops. and because there is no inbuilt initialization, in while loop people commonly use it for checking conditions only as those situations don't need a loop counter. Either way all loops are almost similar and there is nothing that is impossible with any of the loop structures. (Correct me if I am wrong!)

    The simple and modified program for first 10 prime numbers using only "for loop" is posted here. Please have a look and comment.

    #include
    #include
    void main(){
    clrscr();
    int c, i, j, n, count = 0;
    for(i =2;i>0;i++){
    c = 0;
    for(j=2;j if(i%j==0){
    c = 1;
    }
    }
    if(c == 0 && count<=10){
    printf("%d\t", i);
    count++;
    }
    if(count == 10){
    break;
    }
    }
    getch();
    }
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    Yeah, I agree with Sam! 😀 Right dude, it depends on how you use it and yeah, sometimes for can be made a conditional loop and while can be made a counter loop... 😀
  • crazy_sam
    crazy_sam
    Nice question This Question was asked by my Teacher at my 6 weeks training​
    According to my knowledge​
    a for loop repeats for a predefined number of times​

    a while loop repeats as long as a certain condition is true​
    ......​


    This is bull shit. Both loops repeats as long as a certain condition is true, and both loops repeats for a predefined number of times.​
  • PraveenKumar Purushothaman
    PraveenKumar Purushothaman
    crazy_sam
    Nice question This Question was asked by my Teacher at my 6 weeks training​
    According to my knowledge​
    a for loop repeats for a predefined number of times​

    a while loop repeats as long as a certain condition is true​
    ......​



    This is bull shit. Both loops repeats as long as a certain condition is true, and both loops repeats for a predefined number of times.​
    Rightly said.. for ( ; ; ); is an infinite loop!

You are reading an archived discussion.

Related Posts

I could not add new posts in the new pages of my wordpress blog. Is it possible or not? Regular bloggers Help Me
actually i have got a problem,i have got 160 gb but it is showing only 100 gb, so i want to install linux on that remainig part,can it be done,
hey guys how good is windows 7??i have read the reviews and they seem pretty good...but first hand info is always better ...isn't it???!!! is it worth giving up on...
Howdy folks! I had to create a presentation to describe CE. My aim was to tell the 'busy folks' about CE in less than a minute. The feedback I've received...
Hey guys for hyderabad(india) i need your suggestions.i want some ideas on government and private organizations where i can do my major projects.i know some of u guys would have...