menfix
menfix

Reputation: 61

How to force the loop to perform another iteration to zero and close the loop?

In the first example, the loop goes from zero to 9, but I don’t know how to do the same thing in reverse order only.

        size_t i = 0;

        for (i = 0; i < 10; i++)
        { 
            printf("%d\n", i);
        }

0 1 2 3 4 5 6 7 8 9

Here is what I am trying to do but get the last number 1

        for (i = 9; i > 0; i--)
        {
            printf("%d\n", i);
        }

9 8 7 6 5 4 3 2 1

Upvotes: 1

Views: 277

Answers (4)

yaodav
yaodav

Reputation: 1256

in your code, there is a potential error (on the descending loop) you are using size_t as the counter but size_t is an unsigned type that is it always higher than 0, and if by mistake it getting "under zero" it will go to MAX unsigned and it will continue to run. so my suggestion is to use signed ver for loop counter (also unsigned arithmetic is more costly then signed one) and like it ansered to you

int i;
for(i=0; i<10 ; ++i)
{
     //some code
}

for(i=9; i>=0; --i)
{
    //some code
}

Upvotes: 0

Pickle Rick
Pickle Rick

Reputation: 808

for (auto i = 9; i >= 0; --i)
     printf("%d\n", i);

Upvotes: 2

Krzysiek Karbowiak
Krzysiek Karbowiak

Reputation: 1972

There are two canonical loop forms to remember and use in your code. I am using a while loop in both cases to show the difference better.

  1. Looping up
size_t counter = 0;
while (counter != 10)
{
    printf("%d\n", counter);

    ++counter;
}
  1. Looping down
size_t counter = 10;
while (counter != 0)
{
    --counter;

    printf("%d\n", counter);
}

Edit: both forms work with either signed and unsigned loop counters.

Upvotes: 2

Yohan
Yohan

Reputation: 72

You can do this

   for (i = 9; i >= 0; i--)
            {
                printf("%d\n", i);
            }

Upvotes: -1

Related Questions