954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

I have found the difference between 'for' and 'while' loops?

these code, I expect they work the same.

using Code::Blocks as the compiler, the result is differ

result = output 10
return 0

#include <iostream>

int main()
{
    int i = 0;
    while(i < 10)
        ++i;

    std::cout << i << std::endl;
}


result = compile error.

#include <iostream>

int main()
{
    for (int i = 0; i < 10; ++i)
    {
        // random stuff that not bother the result
        --i;
        ++i;
    }

    std::cout << i << std::endl;
}


in the 2nd code, theint i is not defined in the main(), so, because of that, we can use multiple 'for loops' with same iterator(int i)?

unlike 'while loops', the int i declared in the main(), so we can't do the same as the 'for loops'?

well, I posts this because when I search internet for the difference between for and while, many people say it work the same and tell that the only difference is the form.

can anyone confirm of what I "discover"? :)

Vastor
Junior Poster in Training
68 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

Why are you decrementing then incrementing the loop counter in the FOR loop? You should not touch the loop counter...

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
in the 2nd code, the int i is not defined in the main(), so, because of that, we can use multiple 'for loops' with same iterator(int i)?


Why can't you usei in multiple FOR loops if i is defined in main() ?unlike 'while loops', the int i declared in the main(), so we can't do the same as the 'for loops'?
What can't you do the same? What's preventing you from usingi in the WHILE loop and FOR loop?

can anyone confirm of what I "discover"? :)


I'm unclear what you 'discover'? Unless I misunderstand you most of what you're saying is wrong.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 
Why are you decrementing then incrementing the loop counter in the FOR loop? You should not touch the loop counter...

so, I can leave the loop's body empty? whatsoever, thei = i + 1 - 1, right?

1- Why can't you use i in multiple FOR loops if i is defined in main() ?

2- What can't you do the same? What's preventing you from using i in the WHILE loop and FOR loop?

3- I'm unclear what you 'discover'? Unless I misunderstand you most of what you're saying is wrong.

ermm, I'm trying to claim the difference between 'for' and 'while' loop, which is 'for loop' defined the 'counter' in its own block.

but, the (while loop)'s 'counter' must be defined before it's own block itself...

so...

1- can be used, but for while loops, when we define the 'i' we need to define it again and again to reset it, maybe this code can give clue what I'm trying to say...

instead of this code (which will giving potential such variable would clash; if the program is bigger than these)

#include <iostream>

int main()
{
    int counter = 0;
    while (counter < 10)
        // some stuff
        ++counter;

    // counter = 10 here...
        
    counter = 0;
    while (counter < 10)
        // some another stuff
        ++counter;
}

we can use these one...

#include <iostream>

int main()
{
    for (int counter = 0; counter < 10; ++counter)
    {
        // some stuff;
    }
    
    // the 'counter' is not defined here

    for (int counter = 0; counter < 10; ++counter)
    {
        // some stuff.
    }
}


conclusion : I'm claiming that 'for loop' and 'while loop' has different functionality and specific for it own task, even though you can use any of it for the same task.

2- possible, look on the first code, but can become possible source of bugs for a certain program.

3- I hope it's clear now?! :)


P.S. similar to getline(cin, string) and while(cin >> string), you can create a code that has same function using either one of those, thought so, string willseperate each input by whitespace and getline() seperate each input by newline

Vastor
Junior Poster in Training
68 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

> well, I posts this because when I search internet for the difference between for and while,
> many people say it work the same and tell that the only difference is the form.

These two are equivalent:

for( int i = 0 ; i < 10 ; ++i ) {}

{ int i = 0 ; while( i < 10 ) { ++i ; } }
"The for statement
<strong>for( for-init-statement  condition ; expression ) statement</strong>

is equivalent to
<strong>{
    for-init-statement 
    while( condition )  
    {
      statement 
      expression ;
    }
}</strong>

except that 
a. names declared in the for-init-statement are in the same declarative-region as those declared in the condition, 
b. a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition." - <strong>IS</strong>
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

Yes the variables you initialize in the body of the for-loop are local to the loop body's enclosing scope. I think that's written somewhere or something.

In older implementations of C++ that was actually an option for Microsoft's compiler, probably even Version 6.0 of it. Heck there may still be an option to make the variables persist.

pseudorandom21
Practically a Posting Shark
890 posts since Jan 2011
Reputation Points: 216
Solved Threads: 111
 
#include <iostream>

int main()
{
    //{
        int i = 0;
        while(i < 10)
            ++i;
    //}

    std::cout << i << std::endl;
    return 0;
}


Lines 6 and 10. Brackets commented out = compiles. Brackets uncommented = will not compile. Therefore the issue is the scope of the variable i, not whether it is a for loop or a while loop. To make the for-loop compile, declare i higher in the program. Declaring i inside of the parentheses is equivalent to adding the brackets in the above program. It limits i's scope.

VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
 

Yeah actually on Visual Studio 2010 the option is still there, it's under the

project properties -> C/C++ -> Language

tab.

pseudorandom21
Practically a Posting Shark
890 posts since Jan 2011
Reputation Points: 216
Solved Threads: 111
 

@vijayan121
@pseudorandom21

Yeah, I knew it! *noobishly excited* :P

I find it's awkward when two "built-in" code just plainly the same thing, similar is usual but not exactly same...

but to be sure, some claim compiler work differently?! does this mean that these 2 code would work exactly same for some compiler?

Vastor
Junior Poster in Training
68 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 
in the 2nd code, the int i is not defined in the main(), so, because of that, we can use multiple 'for loops' with same iterator(int i)?


Yes you can, at least according to the C\C++ standard, but some compilers will allow the iterator to remain in scope even outside and after the for loop.unlike 'while loops', the int i declared in the main(), so we can't do the same as the 'for loops'?
That's right, except if you do this:

{
      int i = 10;
      while(i > 1)
       { 
         cout << whatever;
         etc., etc.,;
       }
   }
well, I posts this because when I search internet for the difference between for and while, many people say it work the same and tell that the only difference is the form.

Well I guess there is aslight difference, but it doesn't amount to much. You just have to put those extra brackets around the while loop to make them the same. Generally, you use for loops when you know how many iterations you will be doing, and the while loop when you don't know. When you do that, the while loop doesn't have an iterator defined for it, like the for loop, rather it just tests some condition that exists anyway to know when to terminate.

I think it is mostly just a matter of coding style, but I do think that it makes for clearer code when for loops are used when the number of iterations is known and while loops when it's not known.

MandrewP
Junior Poster
111 posts since Nov 2009
Reputation Points: 33
Solved Threads: 21
 

ah, forgot about my last question, after all, I'm confused when a book said 'while' equivalent 'for loop' and really confuse about the scope of the variable that defined from the 'for loop'.

I think the 'mystery' solved now, thnx all for replying

Vastor
Junior Poster in Training
68 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: