7

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.

Michael Young
  • 414
  • 1
  • 7
  • 16

6 Answers6

24

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) {
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 1
    Note that the latter works fine for signed types like `int` but will underflow for types like `size_t` (and thus never terminate). Instead, use `for (size_t index = your_size; index--;)` – Qqwy Nov 29 '18 at 12:04
5

I just want to add to keep in mind that --i decrements first, then checks and i-- checks, then decrements.

GDP
  • 8,109
  • 6
  • 45
  • 82
2

You need the condition to be i>0 (if i starts at 10, then 10<0 is false, so it never executes the loop code).

Todd
  • 1,822
  • 15
  • 18
1

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

is a neat way to express the for loop in @Mark Byers answer.

ps3lister
  • 47
  • 9
1

You are checking i < 0. This is false in the first iteration and thus the loop isn't executed. Change it to i > 0 instead.

Femaref
  • 60,705
  • 7
  • 138
  • 176
0

Change the termination condition from i<0 to i>0

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Oh, this is so different from the FOR loop logic I'm used to in other ancient programming languages. I thought that the condition was testing for i counting down from 10 until i got to 1. This seems counter-intuitive, but it works. Thanks a million. – Michael Young Nov 06 '11 at 00:21