• Post Reply Bookmark Topic Watch Topic
  • New Topic

Loops / Iterations  RSS feed

 
Mario Jorge
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
But your advice paid off and I thank you a lot.

All the best - Mario
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!