ahmedES
ahmedES

Reputation: 49

What is the logic behind this statement: for (--index; index >= 0; --index)?

I found this example in a C language book. This code converts the input number base and stores it in an array.

#include <stdio.h>

int main(void)
{
    const char base_digits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    int converted_number[64];
    long int number_to_convert;
    int next_digit, base, index = 0;

    printf("type a number to be converted: \n");
    scanf("%ld", &number_to_convert);

    printf("Base\n");
    scanf("%i", &base);

    do 
    {
        converted_number[index] = number_to_convert % base;
        ++index;
        number_to_convert = number_to_convert / base;
    }
    while (number_to_convert != 0);

    // now display the number
    printf("converted number =  :");

    for (--index; index >= 0; --index ) 
    {
        next_digit = converted_number[index];
        printf("%c", base_digits[next_digit]);
    }

    printf("\n");
    return 0;
}

I can't understand the last for loop. It should help with reversing the array but I don't understand how!

What does this line mean: for (--index; index >= 0; --index)?

Upvotes: 1

Views: 368

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

Recall that for header has three parts:

  • The declaration/initialization part that gets executed once before the loop,
  • The ending condition checker that gets executed before each iteration, and
  • The part that advances the loop forward to the next iteration

Commonly, the declaration/initialization part sets up a new loop variable. However, it is not required to do so. In particular, when multiple loops share the same loop variable, the initialization portion adjusts the existing value or is missing altogether.

This is exactly what happens in your situation. The do/while loop advances index to one past the end of the array. If you need to start processing from the back of converted_number, you need to decrement index before going into the loop, and then also decrement it on each iteration.

Note that another possibility would be using a while loop with pre-decrement on the index:

while (index > 0) {
    next_digit = converted_number[--index];
    printf("%c", base_digits[next_digit]);
}

Upvotes: 1

Related Questions