Software & Finance





C Programming (Turb C++ Compiler) Loops - for loop, while loop and do while loop





The main difference between for loop, while loop, and do while loop is

  1. While loop checks for the condition first. so it may not even enter into the loop, if the condition is false.
  2. do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false.
  3. for loop is similar to while loop except that
    • initialization statement, usually the counter variable initialization
    • a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement.

The following sample code explains all 3 different loops:


Source Code


bool CopyFile2(const char *srcFileName, const char *destFileName)

{

 

    FILE *istream = fopen(srcFileName, "rb");

    FILE *ostream = fopen(destFileName, "wb");

    if (istream == 0 || ostream == 0)

        return false;

    const int len = 4096;

    char buf[4096];

 

    //////////////////////////////////////////////////////

    while(1)

    {

        if( feof(istream))

            break;

        int nBytesRead = fread(buf, 1, len, istream);

        if(nBytesRead <= 0)

            break;

        fwrite(buf, 1, nBytesRead, ostream);

    }

    //////////////////////////////////////////////////////

 

    //////////////////////////////////////////////////////

    for(;;)

    {

        if( feof(istream))

            break;

        int nBytesRead = fread(buf, 1, len, istream);

        if(nBytesRead <= 0)

            break;

        fwrite(buf, 1, nBytesRead, ostream);

    }

    //////////////////////////////////////////////////////

 

    //////////////////////////////////////////////////////

    do

    {

        if( feof(istream))

            break;

        int nBytesRead = fread(buf, 1, len, istream);

        if(nBytesRead <= 0)

            break;

        fwrite(buf, 1, nBytesRead, ostream);

    } while(1);

    //////////////////////////////////////////////////////

 

    fclose(istream);

    fclose(ostream);

    return true;

}

Output


None