Kochan problem: Chapter 6, Pg.94

Discussion in 'Mac Programming' started by exus69, Dec 8, 2010.

  1. exus69, Dec 8, 2010
    Last edited: Dec 8, 2010

    exus69 macrumors newbie

    Jul 27, 2010
    Following is the problem as given in the "Programming in C" book in Chapter 6, Pg.94

    I was able to reach the basic statements but couldnt go further when logic came into the picture.

    I strongly feel that if statements are gonna be used in this case

    Plz help
  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    I think the key here is:
    integer division - If you divide something by 10 that's an integer, you basically just "shift" your decimal number one position to the right.
    the modulus operator, % - This operator gives you the "Remainder" of a division.

    I would say this is a job for a loop, not an if. You aren't dealing with 3 digits, you're dealing with n digits. I might have a subroutine that returns the number of decimal digits. What's the maximum number of digits an integer can have? What's a way in a loop you could generate numbers that have that many digits?

    Then it's a matter of knowing what to print. I would personally try to keep the list of strings somehow, and grab the right one.

    However, it doesn't look like you've tried anything so far. Maybe you have but gave up and removed the code? Anyway, at this stage you're going to have to experiment sometimes, because the right answer might not always just "pop" into your head.

    Try some more things, post what you try and why it doesn't work and we can help further. I tried to edit this down to not give too much away.

  3. Sydde macrumors 68020


    Aug 17, 2009
    Or do it shorthand using FP math:

    if ( number != 0 )
    - convert the input int to a double
    - get the base 10 log of the number (may require a conversion)
    - the characteristic (integer portion) is the number of decimal digits - 1 (zero-based count)
    - divide the number (the double) by 10 to the characteristic
    - use the integer portion of the number to get the word
    - strip the integer from the number
    - multiply the number by 10
    } while ( 0 != number )

    There are all these nice FP libraries, might as well make use of them.
  4. balamw Moderator


    Staff Member

    Aug 16, 2005
    New England
    So many ways to skin a cat. You could also do it easily using string/char functions. (Must be the old BASIC programmer in me talking).

    Use sprintf to get a string from the int, then just loop though the characters in the string and output the corresponding string for each char.

    Not having read the book myself I don't know what the reader is supposed to know at this point. I doubt either my string approach or Sydde's FP approach are what is intended.


Share This Page