Need help for repetition method!

Discussion in 'C' started by rangerys, Sep 8, 2010.

  1. rangerys

    rangerys New Member

    Joined:
    Sep 8, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi guys,

    I have a question to ask:

    Write a program to read in a positive integer and add up its digits repeatedly until the sum is a single digit. For example, if the integer is 12345, then adding its digits (1 + 2 + 3 + 4 + 5) yields 15, and adding its digits again (1 + 5) yields 6. Hence the answer is 6.

    The tricky part for me is the part where the user can type in any digits he wishes.

    From the angle i see it, I attempted to do smth along this line:

    while x > 1 // x is the number the user entered
    x = x/10
    count++

    using the count i know exactly how many digits are there, from then i proceed to identify each digit,

    x % pow(10,n) * 10 to isolate each digit due to the correlation

    my question is how to i assign the values i looped out to another variable? like digit1 = 2, digit 2 =2 in this looping function?

    thanks for ur help!
     
  2. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in
    All you need to do is to count the number of digits of a given number..then separate the numbers to add up and pass the number formed to the function..the call will be recursive and when the number of digits is 1 return the actual ans...
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice