Decrement a For Loop?

Michael Young picture Michael Young · Nov 6, 2011 · Viewed 66.7k times · Source

I can increment a FOR loop in xcode, but for some reason the reverse, namely decrementing, doesn't work.

This incrementing works fine, of course:

for (int i=0; i<10; ++i) {
    NSLog(@"i =%d", i);
}

But, this decrementing doesn't produce a thing:

for (int i=10; i<0; --i) {
    NSLog(@"i =%d", i);
}

I must have the syntax wrong, but I believe this is correct for Objective C++ in xcode.

Answer

Mark Byers picture Mark Byers · Nov 6, 2011

I think you mean > instead of <:

for (int i = 10; i > 0; --i) {

If you want the values of i to be the same as in the original code except in reverse order (i.e. 9, 8, 7, ..., 1, 0) then you also need to change the boundaries:

for (int i = 9; i >= 0; --i) {