Advertisement
ssoni

checkDigit.c

Jan 3rd, 2022
1,426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1. //Can we write a program that adds up the digits of a number?
  2.  
  3. /*
  4. $ ./checkDigit
  5. Enter a number: 567
  6. The digits of 567 add up to 18
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <cs50.h>
  11.  
  12. int main(void)
  13. {
  14.  
  15.     int num = 0;
  16.     int total = 0;
  17.     int lastDigit = 0;
  18.  
  19.     num = get_int("Enter a number: ");
  20.  
  21.     //Save a copy of the number for use in the final message
  22.     int numSaved = num;
  23.  
  24.     while (num > 0)
  25.     {
  26.  
  27.         //use mod operator (%) to get the last digit
  28.         //eg:  567 % 10 gives a 7, since 567 / 10 is 56 with remainder 7.
  29.         lastDigit = num % 10;
  30.  
  31.         //Add the digit to the running total
  32.         total = total + lastDigit;
  33.  
  34.         //Chop off the last digit, now that we're done with it
  35.         //Divide by 10, but stored in an integer just drops the last digit
  36.         //eg:  567 / 10 = 56.7 but as int its just stored as 56.   The 7 is now gone.
  37.         num = num / 10;
  38.     }
  39.     printf("The digits of %i add up to %i\n", numSaved, total);
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement