Advertisement

for loops- quick question! =)

Started by February 07, 2000 06:18 PM
14 comments, last by Fredric 25 years, 1 month ago
Well, I''m back asking yet another question on C++! Thanks to all of you who posted and gave me a lot of encouragement to continue on with learning C++, as well a big thanks to those who have been answering all my questions (don''t worry, there are still many to come!) As I said, I wasn''t finding it difficult to learn, but a few D.H. Joe''s seemed to want to stop me... I''m going to continue learning C++, and I hope to make a living off of it. My major goal in life is to own a successful software development company. If that falls though, C++ sounds good enough! :-) Here''s my question... The following piece of code is pretty predictable: // looping using for #include int main() { int counter; for (counter = 0; counter < 5; counter++) cout << "Looping! "; cout << "\nCounter: " << counter << endl; return 0; } It''s a loop, and everytime the loops executes, the string Looping! is printed to the screen. No problem there, but when the line of code, for(counter = 0; counter < 5; counter++), this confuses me. I know that this is a loop, and everything is fine and just spiffy, but it is a loop, and to ME, the loop seems to be setting the value of counter to 0 every time it executed. I know this is wrong, or else the loop would never stop. Can someone shoot this out into open for me, it''s quite confusing me a beginner programmer like me! =) twizz24@hotmail.com
3D Math- The type of mathematics that'll put hair on your chest!
The for loop does have kind of a wierd syntax unless your used to it. I''m a while loop user myself. The actual for statement has 3 things in it. The first thing, which for you is counter = 0, is the starting value of loop variable. This is executed right when the loop starts, so it only is executed once. The second thing, counter < 5, is what it checks after each loop. If it returns true then it exit''s the loop, otherwise it keeps on repeating. The last part, counter++, is executed at the end of each loop repetition. The actual for statement doesn''t do much, you have to tell it what to do in each part of the loop. I hope this cleared it up for you.

*** Triality ***
*** Triality ***
Advertisement
OK, here goes...

The first statement is only run once, the first time the program comes to the for loop.

The second statement is called before entering the internal code.

The last statement is called after exiting the internal code.

Here is some piece of code that does the exact same thing as your for loop.
int main(){  int counter = 0;  while( counter < 5 )  {    cout << "Looping! ";    cout << "\nCounter: " << counter << endl;    counter++;  }  return 0;}


Hope that helped. =)
Both of you reccamended while ... so, does that mean that I can always use while instead of for? for is confusing!
3D Math- The type of mathematics that'll put hair on your chest!
Oh yes u can always substitute a while and for and vice versa but for loops are more intuitive, especially when u are dealing with arrays or counters.

Juz be careful to bracket the for loop like
for (..)
{
// code
}
I didn''t recommend using while, I only used it to explain the for-loop.

They are equally powerful though, so you can certainly keep using while loops as long as you wish. Personally I almost always use for-loops because it is much shorter to write.

In general: Most of the time for-loops are used to write iterative code that has a counter variable, like your sample. While loops are used for more complex loops, where the test statement doesn''t necessarily use a counter-below-limit test.

It''s just a matter of convenience, where the for-loop lets you put three statements in one line and still give easy-to-read code.
Advertisement
Don''t forget that in a for loop you can have multiple initializers within the statements:

for (i = 0, j = 10; i < 10; i++, j--)
{
printf("i and j: %d, %d\n", i, j);
}

Will show i incrementing and j decrementing.

The benefit of a while() loop is when you want to write a loop that has no counter:

while (fgets(buffer, 80, file_pointer) > 0)
{
printf("buffer: %s\n", buffer);
}

This will loop as long as fgets reads more then 0 characters. The reason that fgets wouldn''t read more then 0 is if the file is over.

You COULD write it as

for ( ; fgets(buffer, 80, file_pointer > 0; )
{
printf("buffer: %s\n", buffer);
}

But that looks pretty weird -- the empty statements mean "don''t initialize anything" and "don''t modify anything per iteration".. Obviously the while() loop is easier to read.

You can also initialize variables in the for loop. So you can have something like:

for (int counter = 0; counter < 5; counter++)
{
// Do Stuff
}

This way the variable is only in scope for that loop block and it removes a line of code.

-------
Andrew
semi-pseudocode

FOR (
a=0; // make a start at 0
a<500; // loop while a is smaller than 500
a+=2; // increment a by two every time the thing loops
)

{
// your code goes here
}
quote:
Original post by acraig
This way the variable is only in scope for that loop block and it removes a line of code.



That''s not true, the scope of the variable is outside the loop block. You cannot declare the same variable in two for-loops, in the same block, without getting an error from the compiler:

for( int c = 0; c < max; c++ );for( int c = 0; c < min; c++ ); // Error because c is                                // already declared


Just so you know. But as long as we are making short programs, the following code is legal:

for( int c = 0, q = 1; c < 0 && q == 1; c++, q *= 4 );


Of course the code is pretty useless, but at least it shows that you can declare and increment more than one variable in the for-statement.

This topic is closed to new replies.

Advertisement