1

Is there any way of making a for loop iterate a fixed number of times, even though the right side of the interval might be increasing ? I want to do this without declaring an additional variable to use as a copy of the initial inc. For example:

for (i = 0; i < inc; i++)
{
  if (condition) 
  {
     inc++;
  }
}

I am pretty sure that if inc increases, the for will execute more than inc - 1 times. How can I iterate exactly inc times, without using a copy of inc ?

rares985
  • 341
  • 3
  • 15
  • 1
    You aren't looping a fixed number of iterations so you shouldn't use a for loop, should be a while. I'd tear you a new one in code review even if you got this to work somehow.... – Tony Hopkinson Jan 10 '15 at 12:00

2 Answers2

2
for (i = inc; i > 0; i--) {
    if (condition) {
        inc++;
    }
}

This would work since you only assign inc once.

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
0

I think you are possibly looking for a 'range', you don't say what language its for but in python something like:

 inc = 2
 for i in range[0:10]:
      if i > inc:
           inc=inc+1
      print inc
user3062260
  • 1,584
  • 4
  • 25
  • 53