From the "Programing in Objective C" (Kochan):
Program 5.8 prompts the user to enter a number and then proceeds to display the digits from that number from the rightmost to leftmost digit.
// Program to reverse the digits of a number
#import <Foundation/Foundation.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, right_digit;
NSLog (@"Enter your number.");
scanf ("%i", &number);
while ( number != 0 ) {
right_digit = number % 10;
NSLog (@"%i", right_digit);
number /= 10;
}
[pool drain];
return 0;
}
My question is: what happening when user types in single digit number- 1 to 9 ? I couldn't find any material about such case. After compilation the program just proceed with returning that single digit. Why is that? I was trying to come up with code for this task and spend literally 2 hours, trying to incorporate loops and decision making for this " if number is single digit" problem. And the solution was so ignorant!
The modulo operator gives you the remainder after a division. If yo have 8 % 10 the result is 8 because 8 / 10 is 0 with a remainder of 8. You get the same result if you have 38 % 10, 38 / 10 is 3 with a remainder of 8.
edit: Modulo is what you normally learned as the first division in elemantary school. It is funny that the most children have no problem with modulo but when they learned that 8 / 10 is 0.8 they have problems understanding modulo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With