Thread: Additioning of digits!!

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    12

    Question Additioning of digits!!

    it's a program gets a number and adds it's digits,though i don't know
    how the commented expressions does it!!!

    Code:
    main() {
            int x, i, m=0;
            scanf( " %d " ,&x );
                    for( i=0 ; x>0 ; i++)
                    {
                      m += x % 10 ; /* */
                      x /= 10;  /* */
                    }
              printf(" %d ", m );
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Line 6 and line 7, are using the fact that our number base is 10. So every time through the for loop, one digit from the right hand side is "peeled off", and separated from the rest of the number. m gives you a running sum of the digits.

    When x == 0, the positive integer, has had it's digits all peeled off.

    Don't be afraid to put a printf() statement inside the for loop, followed by a getchar(), so you can see what digit is being removed, and get a better feel for it. That's a big plug with programming - you don't have to just theorize - you can often times, quickly try it.

  3. #3
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    Also, not a big deal, but your for loop could easily be used as a while loop. Therefore no need for integer i.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sum of k-digits in ^n
    By MoZak in forum C Programming
    Replies: 27
    Last Post: 11-21-2011, 09:53 AM
  2. Digits...
    By Murk in forum C Programming
    Replies: 8
    Last Post: 02-05-2008, 02:16 PM
  3. Help with digits
    By jrice528 in forum C++ Programming
    Replies: 4
    Last Post: 10-03-2007, 06:04 PM
  4. get all the right digits
    By mag_chan in forum C Programming
    Replies: 6
    Last Post: 11-27-2005, 06:16 AM
  5. Two digits
    By cyberCLoWn in forum C++ Programming
    Replies: 4
    Last Post: 02-23-2004, 01:53 PM