Thread: how to sum the digits of a number?

  1. #31
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    sorry
    679->4

    i tried to do the double loop thing.
    its not working

    Code:
    printf(" enter number  ");
    
    scanf("%d", &digit);
    copy = digit;
    do
    {
        sumb=0;
       do
        {
          sumb = sumb + copy % 10;
    
          copy = copy / 10;
    
           if (sumb < 10)
              {
               flag = 1;
              }
    
    
        } while (copy != 0);
        copy=sumb;
    } while(flag != 1);
    printf("%d",sumb);

  2. #32
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    To make it work, you would have to pay a tiny little bit of attention to what's going on. I would have thought that all that bold I used before would have pointed out your errors with flag (one, that it gets set in inappropriate places, and two, that it never gets unset once it becomes set). Fortunately there's no earthly reason to use this flag, so getting rid of it won't hurt a bit. (Notice that if you finish the loop, and at that point and at that point only sumb is less than 10, then you can stop.)

  3. #33
    Banned
    Join Date
    Oct 2008
    Posts
    1,535
    i fixed it
    thanks

  4. #34
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Code:
    printf(" enter number  ");
    scanf("%d", &digit);
    while(digit > 10) {
        do
        {
            sumb += digit % 10;
            digit = digit / 10;
        }while(digit / 10 >1);
        digit = sumb;
    }
    printf("%d", 23);

  5. #35
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by C_ntua View Post
    Code:
        }while(digit / 10 >1);
    Oddly enough that line is the same as:
    Code:
    } while (digit >= 20);
    But it looks like the answer is correct anyway...
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sum of digits of an integer: Odd or Even?
    By Devolution in forum C Programming
    Replies: 14
    Last Post: 03-06-2009, 06:24 PM
  2. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  3. xor linked list
    By adramalech in forum C Programming
    Replies: 23
    Last Post: 10-14-2008, 10:13 AM
  4. Looking for constructive criticism
    By wd_kendrick in forum C Programming
    Replies: 16
    Last Post: 05-28-2008, 09:42 AM
  5. Help on Sum of Digits Entered
    By SkinnyK in forum C Programming
    Replies: 5
    Last Post: 05-14-2008, 05:16 AM