I wanted to make sure that the program would still tally the individual digits properly even if the user entered a negative integer, but after some tinkering this is the best I could come up with:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, digit, total;
NSLog (@"Enter your number.");
scanf ("%i", &number);
total = 0;
while ( number < 0 ) // using the while statement to force the entered integer to positve
{
number *= -1;
}
while ( number != 0 )
{
digit = number % 10;
total += digit;
number /= 10;
}
NSLog (@"The sum of the digits is %i.", total);
[pool drain];
return 0;
}
That finally worked, but it ain't pretty. That first while statement seemed like a real roundabout way to get there. Originally my thinking was more along these lines:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, digit, total;
NSLog (@"Enter your number.");
scanf ("%i", &number);
total = 0;
number = (unsigned) number +0;
while ( number != 0 )
{
digit = number % 10;
total += digit;
number /= 10;
}
NSLog (@"The sum of the digits is %i.", total);
[pool drain];
return 0;
}
But that didn't work. The line:
number = (unsigned) number +0;
doesn't seem to do the trick. What am I missing here? Is there a simple way to force and integer to be positive? I feel like it has something to do with converting it to and unsigned int, right? But I can't figure out how to do it.
Thanks.
--Dave--