Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Token Homework

  1. Sep 24, 2010 #1
    Object: Write a program that read digits and composes them into integers. For example, when you read 123( in characters) the program should print: "123(in integers) is 1 hundred and 2 tens and 3 ones".

    My first attempt is first read the number as a string then convert its characters to integers then store them in another int vector. To print the result, I used switch to determine how many items are there in the vector (i.e if read 1234 (4 items) then print 1 thousand 2 hundred....) but then I realize it not a good way. How about if people read in 10 characters??

    Please give me some idea to start.
  2. jcsd
  3. Sep 24, 2010 #2
    Don't ask hw questions :P

    Proceeding along your original route of storing the char input and transforming it into an int vector:

    Instead of switch/case, I'd create an array/vector of strings, with each string having the name "ones","tens","hundreds",...

    Then just create a loop that runs backwards from the length of the input string down.

    A couple details: you can determine how big an array is using sizeof( yourArray ). You might also want to do a preliminary parse to remove things like commas from the input.
  4. Sep 24, 2010 #3
    Here we go:

    Code (Text):
    print "$_ (in integers) is";
    @_=split //;
    for(0..$#_) { print " ".(($_>0)?"and ":"")."$_[$_] ".(qw/one ten hundred thousand ten-thousand hundred-thousand million ten-million hundred-million billion ten-billion hundred-billion trillion ten-trillion hundred-trillion quadrillion/)[$#_-$_] . (($_[$_]==1)?"":"s"); }
    print "\n";
    Seriously, though:

    1) Homework = not here, see the sticky.
    2) Clean your input (make sure there are no other characters like decimal points, commas, other characters, etc.)
    3) Make one array of names (as suggested above), like "one", "ten", "hundred", etc. However, note: there's no "s" on the end. There's a difference when you print them between saying "5 hundreds", "1 hundred", or "0 hundreds". Only print an "s" after the place's name if the value is 1!
    4) Make a second array of the characters that were input
    5) Loop through the character array normally, but loop through the "place name" array differently-- start in the middle (where appropriate), and work backwards, rather than forwards.

Share this great discussion with others via Reddit, Google+, Twitter, or Facebook