programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Loops / Iterations

Mario Jorge
Greenhorn
Posts: 16
Hi All - I have to answer the below for an assignment in College... but the answers I'm not 100% sure on!!

Might be right... but if you wouldn't mind casting your eye over them... much appreciated.

How many iterations do the following loops carry out? Assume X is an integer variable that does not get changed by the loop body!
A: for (x=1; x<=10; x++) = 9
B: for (x=0; x<=10; x++) = 10
C: for (x=10; x>=0; x--) = 10
D: for (x=-10; x<=10; x++) = 20
E: for (x=10; x>=0; x++) = 10
F: for (x=-10; x<=10; x+ =2) = Not sure
G: for (x=10; x<=10; x+ =3) = Not sure maybe 0?

Thanks a lot - M

Henry Wong
author
Sheriff
Posts: 23295
125
• 1
Mario Jorge wrote:
How many iterations do the following loops carry out? Assume X is an integer variable that does not get changed by the loop body!

It takes only  a minute to write a quick program and see for yourself.  Why don't you just try it?

Hint: I just looked at the first one. And you were incorrect -- which is why I am suggesting you try it yourself.

Henry

Mario Jorge
Greenhorn
Posts: 16
Henry Wong wrote:
Mario Jorge wrote:
How many iterations do the following loops carry out? Assume X is an integer variable that does not get changed by the loop body!

It takes only  a minute to write a quick program and see for yourself.  Why don't you just try it?

Hint: I just looked at the first one. And you were incorrect -- which is why I am suggesting you try it yourself.

Henry

Thanks Henry - TBH I never thought of it and you were right I was way off.

All the best - Mario

Campbell Ritchie
Marshal
Posts: 56599
172
Those are all fencepost numbers.

How many posts do you need to erect a 100‑foot long fence if the posts go at 10‑foot intervals?

Campbell Ritchie
Marshal
Posts: 56599
172
• 1
Welcome to the Ranch

Maybe you are right. If you write the parts of the for loop on paper, like this, you can count how many times each runs:-Note OP's loops use <= and >= which I think are harder to read than < and >. I prefer to stick to < and > if possible. The way I have written the loop, i goes out of scope when the loop finishes, so it has no value at the end of line 11.