How to create this forloop

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 563 Views - Last Post: 09 October 2012 - 05:33 PM Rate Topic: -----

#16 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3163
  • View blog
  • Posts: 9,554
  • Joined: 05-May 12

Re: How to create this forloop

Posted 09 October 2012 - 05:33 PM

Do you have any guarantees of the following?

Quote

end == begin + change * k
where
k >= 1


If so. You can just swap begin and end and flip the sign of change if begin is greater than end. Remember that multiplication is commutative: 1 * 2 * 3 == 3 * 2 * 1.

If you really need to numbers to go from begin to end, then you can probably set up a loop that breaks out after the loop variable has become equal to end and the appropriate computation has been done. Remember that the condition for a for loop need not be the loop variable. So you can do something like:
for(int i = begin; true; i += change)
{
    do work with i
    break out of loop when i equals end
}


Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2