# Posted By

bobtiki on 01/06/09

# Statistics

Viewed 158 times
Favorited by 0 user(s)

# Programming in Objective-C 2.0, Chapter 6, Exercise 6, Horribly broken

/ Published in: Objective C  Thanks for the hints, DC NSCoders. I've got a working version now. It might not be the most elegant, but it should work for all signed 32-bit integers.

> Write a program that takes an integer keyed from the terminal and extracts and displays each digit of the integer in English. So, if the user types in 932, the program should display the following:

nine
three
two

> (Remember to display 'zero' if the user types in just 0.) Note This exercise is a hard one!

The trick is, in the book, you haven't yet learned about arrays, so the solution must not include arrays. Nor do you "know" about file operations, string operations, or most other things that might prove useful here.

Copy this code and paste it in your HTML
`#import <Foundation/Foundation.h> // numbers to word-numbers int main (int argc, const char * argv[]) {    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];	int number, remainder, leftDigit, counter;	BOOL tooBig; 	// This should now work for every 32-bit signed integer (fingers crossed) 	NSLog(@"Enter a valid 32-bit signed integer (from -2147483648 to 2147483647:");	scanf("%i", &number); 	// flip negative numbers to positive, and check for special case -2147483648 	if (number < 0) {		if (number == -2147483648){			NSLog(@"negative\ntwo\none\nfour\nseven\nfour\neight\nthree\nsix\nfour\neight");			return 1;  // just to prove to myself that the program exited here with this value		}		else {			number = -number;			NSLog(@"negative");		}	} 	if (!number) {		NSLog(@"zero");	} 	// to prevent leading zeros, check for first counter that will divide into the number 	if (1000000000 > number)		tooBig = TRUE; 	for (counter = 1000000000; counter >= 1; counter /= 10) {		if (tooBig == TRUE && counter > number)			continue;		else			tooBig = FALSE; // trips the switch so all subsequent zeros will be counted 		remainder = number % counter; 		if (remainder == number)			leftDigit = 0;		else			leftDigit = (number - remainder) / counter; 		// Debugging printout for checking variable numbers		// NSLog(@"R%i-N%i-C%i-L%i", remainder, number, counter, leftDigit); 		switch (leftDigit) {			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;			default:				break;		}		number = remainder;	}       [pool drain];    return 0;}` Subscribe to comments