Brandi Love

Ranch Hand

Posts: 133

posted 13 years ago

I had an assignment in which I had to write a program in which the user enters an integer between 10,000 and 99,999. The program then takes the number, strips the individual digits off (without a tokenizer) and adds them and displays the digits with the result. I figured out that you cold strip the ivdividual digits off by taking the original number and doing a %10 to get the last digit, and then to get the next digit divide the original integer by 10 (and the next by 100, the next by 1,000, etc) and again doing a %10 to get the digit. Now I have to rewrite the program so that it will do the same for ANY positive integer, and I haven't the faintest clue where to start. I know I have to rewrite the equation somehow, but thats about it. Any help would be most greatly appreciated. Here is my code for the original program:

posted 13 years ago

you could write a loop that divides by 10, and when you get a result of 0, you know you're done. i.e. inpu 123

divide by 10, get 12.

divide by 10, get 1

divide by 10, get 0. you're done. you did 3 divisions, so you have a 3 digit number.

or, you could read in a string, get the length, then translate it to an integer

divide by 10, get 12.

divide by 10, get 1

divide by 10, get 0. you're done. you did 3 divisions, so you have a 3 digit number.

or, you could read in a string, get the length, then translate it to an integer

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors