# Thread: Ugly loop!

1. ## Ugly loop!

Hi every body!
Can you tell me what this strange code do?

for (int i = 0; i < 4; i++)
for (int i = 0; i < 2; i++)
for (int i = 0; i < 2; i++)
cout <<"Done!" <<endl;

2. It outputs "Done!" 16 times while iterating through some loops. It might be more clear if we indent:
Code:
```for (int i = 0; i < 4; i++)
for (int i = 0; i < 2; i++)
for (int i = 0; i < 2; i++)
cout <<"Done!" <<endl;```

3. Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!
Done!

4. You'd get the same result from using one loop (though I imagine that the code you gave was originally intended as a demonstration of some loop principles):
Code:
```for (int i = 0; i < 16; i++)
cout << "done" << endl;```
When posting code, be sure to use code tags. Place [ code ] at the beginning of your code, and [ / code ] at the end (without the spaces), and it will format the code so it looks better on the board. It puts it in a more appropriate font and preserves indentation.

5. As said...it's just a REALLY ugly and confusing way to print "done". You'd never need to nest for loops to do such a simple task.

...And it's usually a good idea to enclose your for, if, and else statements in braces {}.

Doing so will illustrate much more clearly where each statement is being applied to.

6. You usually see code like that on exams. Testing your ability to read syntax.

7. Originally Posted by ameber
Hi every body!
Can you tell me what this strange code do?

for (int i = 0; i < 4; i++)
for (int i = 0; i < 2; i++)
for (int i = 0; i < 2; i++)
cout <<"Done!" <<endl;
What the hell is wrong with people? Why don't you compile it and find out for yourself?

Quzah.

8. Originally Posted by quzah
What the hell is wrong with people? Why don't you compile it and find out for yourself?
Probably because he's sitting in his computer lab taking an exam and was lookin for a quick answer, so he fired up IE while the instructor wasn't watching

9. Yeah.... a "What does this do?" isn't the brightest question to ask.

Anyway Ameber, you could say that the nested loops work from the "inside, out."(At least, that's a good way to visualize it) The inner-most loop executes until it's done, then the outer for loops will execute. This will continue until the outer-most loop's condition statement is false.

4*2*2 = 16 executions.

Compile it yourself next time.

10. ## right!!

you are right! I'm sleeping instead of working hard!

Popular pages Recent additions