Purposes of Different Kinds of Loops - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Purposes of Different Kinds of Loops

sashimi17sashimi17 DallasPosts: 7Member

I've wondered ever since I started learning to code what the best kind of tasks to use the different kinds of loops for are.

What's a common situation in which it's most efficient to use a while loop? What's the best time to use a for loop?

Perhaps most importantly, when do I want to use a do-while loop instead of a while loop? I know (or at least I think) that a do-while loop will always execute at least once, whereas a while loop might not execute at all if the initial condition is not met. In what kind of situation is a do-while loop most useful?

Thank you.

Comments

  • IcepickleIcepickle GermanyPosts: 49Member
    edited August 2014

    a good example of a do while loop is buffered reading, where you would read a stream for example, until there is no more data to get, this would go in pseudo code (no real functionalities, possible scenarios) rather like this:

    var lastReadCount, buffer = [], bufferSize = 1024;
    do 
    {
        lastReadCount = file.read(buffer, 0, bufferSize);
        // write content of buffer to stream
    } while (lastReadCount > 0);
    

    another possible variation would be (which would in this case dupplicate code (2 possible places where you would need to correct errors, in case there are some))

    var buffer, bufferSize = 1024,
        lastReadCount = file.read(buffer, 0, bufferSize);
    
    while (lastReadCount > 0) {
    // write content of buffer to stream (notice that you need 2 read statements)
        lastReadCount = file.read(buffer, 0, bufferSize);
    }
    

    a for loop you rather use when you are working with an indexer, and with a distinct number of items

    for (var i = 0; i < length; i++) {
        // do stuff (preferably with the indexer (i))
    }
    

    which would also work, in case you changed it to

    var i = 0;
    while (i < length) {
        // do stuff  (preferably with the indexer (i))
        i++;
    }
    

    or by using

    var i = 0;
    do {
        // do stuff  (preferably with the indexer (i))
    } while (++i < length);
    

    which clearly complicates the readability, and your required attention span (remembering to increase the iterator, so that you don't get stuck in an infinite loop, etc...)

    maybe as a last info, when deleting members out of an array, it is also preferred to use a for loop, with a decreasing indexer

    var length  = bigArray.length;
    for (var i = length; --i >= 0;) { // you could notice that i is decreased inside of the evaluator, and not necessary at the end
        if (i % 2 == 0) {
            // remove element from array & continue
            continue;
        }
    }
    
Sign In or Register to comment.