Objective C "do - while"
An example of one of the exercises in a book I'm 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 that the while statement shows (input / = 10), which, if I understand it correctly, basically means (input = input / 10). Now, if this is the case, why isn't the loop running continuously? I mean, even if you have to divide 0 by 10, then this will still extract a number. If the user had to enter "50607", he would first disable "7", then "0", and so on. Etc., but why does it break out of the loop after removing the "5". Wouldn't the answer after "5" be the same as "0" between 5 and 6 in the program?
a source to share
You seem to be confused about the difference between /
and %
. This cycle divides input
and uses the factor, not the remainder. For your example 50607
, the loop has 5 iterations:
-
input = 50607
-
input = 5060
-
input = 506
-
input = 50
-
input = 5
After the last iteration, input
becomes 0
, and the loop ends.
a source to share