Amazon.com Widgets How to parse a number...
Welcome, Guest. Please login or register.
Did you miss your activation email?
September 30, 2014, 06:50:35 AM
Home Help Search chat Login Register 
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+ Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+ Old Stuff
| |-+ Chapter Study
| | |-+ Chapter 5 - Program Looping
| | | |-+ How to parse a number...
Pages: [1] Go Down
Print
Author Topic: How to parse a number... (Read 3441 times)
daviddelmonte
Full Member
***
Posts: 123



WWW Email




on: November 21, 2009, 03:28:41 PM

There is an exercise in Ch. 5 that says to "write a program that calculates the sum of the digits of an integer. "

I would like to know how to capture each digit so I can transform it to a corresponding letter.

Help would be really appreciated..

David

Logged
toby
Full Member
***
Posts: 104






Reply #1 on: November 21, 2009, 04:07:50 PM

I would suggest starting off by looking at program 5.8 which shows you how to break an integer down into individual digits. From there you can use various approaches to attach it to a corresponding letter. You could hard code a bunch of if or switch statements, but I would suggest if you are looking to transform it to a single letter then a char array would be the simplest choice. For example if the letter you had in mind was the first letter in the spelling of that digit then you could do something like this :

Code: (Objective-C)
//setup a char array
char num_alpha = {'z', 'o', 't', 't', 'f', 'f', 's','s','e','n'}; // the first letter of each digit 0-9 or whatever 10 letters you want

then use code similar to the main while loop in 5.8 to break the integer down into separate digits. Where you want to convert the digit captured (in the example it is captured in the variable "right_digit") then you could use a line like this (this one assumes your printing it, you could do anything with the same principles):

Code: (Objective-C)
NSLog("The first letter of %i is %c", right_digit, num_alpha[right_digit]);

right_digit contains an int with the value of the right most digit in your original number and each time through the loop works its way to the left of the original number. You can use that as an index for num_alpha like num_alpha[right_digit], this gives you the value stored in num_alpha at the position stored in right_digit. The array is 0 based, so if right_digit contains 0 you will get 'z' (the first element), if it contains 6 you will get 's' which is the 7th element.

There are a few other ways you could do things if you are looking for a different effect, in the end the basis of it will probably revolve around the concept of the 5.8 program. Alternatively you could (assuming we are only working with primitive data types), read (through scanf) the number into a char array as a string, then use something like the atoi function(which i think is in the ctype.h header file, or make your own) to convert each digit to a number as required. In a primitive char based string each character is stored in a separate array element with the last element containing a zero-byte as a marker for the end of the string. This means first the your number is already stored as separate digits, second your char array needs to be 1 longer than the maximum you intend to every put in it (it will let you over flow it and crash your program). Also characters in strings are stored as numbers which represent that character, so the character 1 is represented by a number that is not 1 and if you treat the character 1 as a number it will let you do calculations with it but you will get results based on the number that is being used to represent 1 (which will likely be 49 assuming an ascii character set). This path is pretty valid and you can do allot of things, it is however fraught with danger c style char strings are a pain to manipulate but are covered in chapter 13. In the introduction to foundation framework you get introduced to allot of much better ways to deal with strings using cocoa objects, these however do not work with primitive data types and scanf only works with primitive data types, so if you want to bridge that gap you probably want to wait till you read up till there rather than have me explain it badly.
Last Edit: November 21, 2009, 04:20:38 PM by toby Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #2 on: November 21, 2009, 04:13:54 PM

Thanks Toby, I noticed that 5.8 seems to parse from right to left.. I don't understand how you parse from left to right?

David
Last Edit: November 21, 2009, 04:21:02 PM by daviddelmonte Logged
toby
Full Member
***
Posts: 104






Reply #3 on: November 21, 2009, 05:01:28 PM

In short, you don't. You can parse from right to left, and save each digit as you go (again best option here is an array of some kind) and then use the separated digits you have saved  to work with them in the order of your choice.
Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #4 on: November 21, 2009, 05:55:48 PM

OK. Weird but ok..

Thanks Toby. I appreciate your patience...

David
Logged
toby
Full Member
***
Posts: 104






Reply #5 on: November 21, 2009, 06:37:50 PM

An int holds the value of a number as a string of binary digits, it's not indexed by decimal digits or anything(some languages do this), you can store a number originally written in various different bases (eg hex or whatever) into an int, and again they can be output from an int in various bases also, every number held in an int is converted down to the binary representation of the original number for storage in ram and all manipulation. The only way you can get an int to break down into its separate digits is mathematically, and unless you know how many digits there are then you can't break it down from left to right, you have to go right to left.

Your other reasonable options are to start off with a string instead that contains number characters. Strings are an array of characters with each element containing a separate character, as arrays can be indexed this saves some work in some cases, but can add some pain also.

I'll perhaps have a bash at trying to knock up some examples of ways you could go about this as rough code outlines sometime tomorrow, when I've not been drinking (its not good for the code), if you are still stuck. I would probably suggest using an array adding the right most digit each time through the loop, then doing whatever you like with them as you could refer to each digit by index from left to right at your will(ie you could store leftmost at index 0).
Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #6 on: November 21, 2009, 08:01:53 PM

Thanks Toby.. I think that I should try to decompose the sequence according to the instructions - ie right to left.

One area that remains vague (as opposed to the billion areas I haven't a clue about), is the relationship between classes/objects and methods. I need to practice how to pass parameters and data between them.

Anyway, after a few scotches myself, it's probably not the right time.

Have a good evening..

David
Logged
toby
Full Member
***
Posts: 104






Reply #7 on: November 23, 2009, 09:33:33 AM

Ok, I was full of crap... this isn't really a great way to do it, I would still suggest the right to left approach and build up a list of some kind to work from how you like. However I did manage to work out how to work from left to right (in a bit of a mess that could do with minor fixing but my xCode is pretty messed up an needs reinstalled, its not very readable either):

   
Code: (Objective-C)
int number = 0;
int numPart = 0;
int currentNumber = 1;
int rNum = 0;

printf("Enter a number to break down: ");
scanf("%d", &number);

if (number < 0) {
printf("-");
number = -number;
}

while (currentNumber < number) {
numPart = number;
while (numPart / 10 >= currentNumber) {
numPart /= 10;
}

rNum = numPart % 10;
currentNumber = numPart;
currentNumber++;

printf("%i", rNum);

}

Oh yeah it also cuts off a leading 0 if one is present, it only works with the numerical value.

The theory here is using the same method as program 5.8 really. As 5.8 works from the right it eliminates the right most digits, here we copy the original number, eliminate all the right most digits till there is only the left most digit left, print that out, and start again at the right eliminating till there are 2 digits left then using the % operator to determine the right most of those 2... The variable number hold the original int, the currentNumber accumulates the left digits that have been processed so far, the rNum contains the digit we want, the numPart is used to hold one more digit than the currentNumber each pass through the loop. 
Last Edit: November 23, 2009, 09:45:39 AM by toby Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #8 on: November 23, 2009, 09:49:50 AM

That is cool!!!! I am going to be out till later today, and have to throw up some web site designs for a client. I will look at the code in detail this evening..

Way to go Toby!!

David
Logged
toby
Full Member
***
Posts: 104






Reply #9 on: November 23, 2009, 01:43:16 PM

Well have fun and if you find a problem with it be sure to let me know. I was trying to iron a few things out and was originally using NSLog over printf, however for some reason xCode is giving me bad access exceptions and my programs are crashing every time I use anything from the foundation framework, so its brought down to plain c else I couldn't get it working at all. I'm off to reinstall xCode and frameworks.
Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #10 on: November 23, 2009, 02:31:18 PM

Thanks again Toby. You know you need different xCode versions for Leopard vs SL...

I'm going to modify the routine, so that before printing, it converts a number to a letter. It's also practice at building methods. I'll move code into Interface and Implementation sections.

David
Logged
toby
Full Member
***
Posts: 104






Reply #11 on: November 23, 2009, 03:13:55 PM

No worries.

Yeah I know, I upgraded both at the same time, I'm not sure what happened, maybe one of the header files got corrupted or something, it ripped it all out and installed it again, works now  Smiley It probably didn't effect all of the foundation framework but it did seem to be messin up whenever I tried to use it, its the kind of error I would expect in certain cases if I had done something like drop the @ before a string literal in a NSLog call, but it seemed to be coming up everywhere on stuff that previously worked. I might have clicked somewhere and moved or edited something when I was really tired or something stupid like that and ended up with something not right.

What is the plan for converting numbers to letters? Is there a purpose or just something you want to try? Have fun.

Toby
Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #12 on: November 23, 2009, 09:04:42 PM

Toby, glad you got your system straight..

 Smiley

Regarding conversions... it's crude but it works....

Code: (Objective-C)
#import <Foundation/Foundation.h>


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
int number = 0; 
int numPart = 0; 
int currentNumber = 1; 
int rNum = 0; 


do {
number = 0;
numPart = 0;
currentNumber = 1;
rNum = 0;
printf("\nEnter a number to convert or press 999 to exit: "); 
scanf("%d", &number); 



while (currentNumber < number)

numPart = number; 
while (numPart / 10 >= currentNumber) { 
numPart /= 10; 


rNum = numPart % 10; 
currentNumber = numPart; 
currentNumber++;
//printf("rNum = %i\n", rNum);

switch (rNum) {
case 1:
printf("\n1 = A");
break;
case 2:
printf("\n2 = B");
break;
case 3:
printf("\n3 = C");
break;
case 4:
printf("\n4 = D");
break;
case 5:
printf("\n5 = E");
break;
case 6:
printf("\n6 = F");
break;
case 7:
printf("\n7 = G");
break;
case 8:
printf("\n8 = H");
break;
case 9:
printf("\n9 = I");
break;
case 0:
printf("\n0 = J");
break;


default:
printf("\nBad Number - try again or key 999 to exit");
break;
}
//printf("%i\n", rNum);
}

}
while (number != 999);

printf("\nEnd of Program");

    [pool drain];
    return 0;
}

Logged
Pages: [1] Go Up
Print
Jump to:



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.