views:

108

answers:

1

The example for one of the exercises in the book I am reading shows the following code:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int input, reverse, numberOfDigits;

    reverse = 0;
    numberOfDigits = 0;

    NSLog (@"Please input a multi-digit number:");
    scanf ("%i", &input);

    if ( input < 0 ) {
        input = -input;
        NSLog (@"Minus");
    }

    do {
        reverse = reverse * 10 + input % 10;
        numberOfDigits++; 
    } while (input /= 10);

    do {
        switch ( reverse % 10 ) {
        case 0:
            NSLog (@"Zero");
            break;
        case 1:
            NSLog (@"One");
            break;
        case 2:
            NSLog (@"Two");
            break;
        case 3:
            NSLog (@"Three");
            break;
        case 4:
            NSLog (@"Four");
            break;
        case 5:
            NSLog (@"Five");
            break;
        case 6:
            NSLog (@"Six");
            break;
        case 7:
            NSLog (@"Seven");
            break;
        case 8:
            NSLog (@"Eight");
            break;
        case 9:
            NSLog (@"Nine");
            break;
        }
        numberOfDigits--;
    } while (reverse /= 10);

    while (numberOfDigits--) {
        NSLog (@"Zero");
    }


    [pool drain];   
    return 0;   
}   

My question is this, the while statement shows (input /= 10) which, if I understand this correctly basically means (input = input / 10). Now, if that is true, why doesn't the loop just run continuously? I mean, even if you were to divide 0 by 10 then that would still extract a number. If the user was to input "50607", it would first cut off the "7", then the "0", and so on and so on, but why does it exit the loop after removing the "5". Wouldn't the response after the "5" be the same as the "0" between the 5 and the 6 to the program?

+5  A: 

You seem to be confused about the difference between / and %. That loop is dividing input and using the quotient, not the remainder. For your example of 50607, the loop goes 5 iterations:

  1. input = 50607
  2. input = 5060
  3. input = 506
  4. input = 50
  5. input = 5

After the last iteration, input becomes 0 and the loop ends.

Carl Norum