English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

How many times will the following loop execute?

for (int i = 20; i <=500; i *=5)
{....}

I know that it loops 3 times, but I can't explain why. I know it has something to do with the " i *=5 ". Can someone please explain. Thanks.

2007-12-18 14:54:28 · 4 answers · asked by metalikidd7 2 in Computers & Internet Programming & Design

4 answers

Do a code trace. Follow the value of i

i starts as 20.
After the loop finishes, i *= 5 means 'multiply i * 5 and put the result back in I, so after the first iteration, i is 20 * 5, or 100.
After the next iteration, it will be 100 * 5, or 500.
500 is still small enough (barely) to stay in the loop, so the next iteration causes i to be 2500, which is too large, and the loop quits.

2007-12-18 15:04:04 · answer #1 · answered by Anonymous · 0 0

Just walk through it:

1. i starts out at 20. The condition 20 <= 500 is true so the loop executes (#1). Then i is incremented to 20*5, which is 100.
2. Now, 100 <= 500 is true so the loop executes again (#2) and i is set to 100*5, which is 500.
3. 500 <=500 is true, so the loop executes a 3rd time, and i gets set to 500*5.
4. At the next iteration, the conditional i<=500 is now false, so control passes to the next statement after the loop.

2007-12-18 15:04:23 · answer #2 · answered by daa 7 · 0 0

well, this loop starts at twenty and goes to 500. If you were incrementing by one then you would have 480 times through the loop.

Since you are incrementing by a multiple of 5, you will have the first iteration, i=20, the second i=100, the third, i=500.
After that i=2500 which is greater than 500 so the loop ends.

Hope that helps

2007-12-18 15:00:21 · answer #3 · answered by jjhavokk439 2 · 0 0

The following will happen when this for loop happens, I will use loop code to be any code that is inside the brackets:

1. I = 20;
2. is I <= 500 (yes, it is 20)
3. since it is, execute loop code
4. I *= 5 (equivalent to I = I * 5), since I was 20, it is now 100
5. is I <= 500 (yes, it is 100)
6. since it is, execute loop code
7. I *= 5, since I was 100, it is now 500
8. is I <= 500 (yes, it is 500)
9. execute loop code
10. I *= 5, since it was 500, it is now 2500
11. is I <= 500 (no, it is 2500)
12. loop is done (loop code does NOT execute again).
So it executes 3 times

2007-12-18 15:01:19 · answer #4 · answered by johnnyloot 3 · 0 0

fedest.com, questions and answers