Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Can we write a program that adds up the digits of a number?
- /*
- $ ./checkDigit
- Enter a number: 567
- The digits of 567 add up to 18
- */
- #include <stdio.h>
- #include <cs50.h>
- int main(void)
- {
- int num = 0;
- int total = 0;
- int lastDigit = 0;
- num = get_int("Enter a number: ");
- //Save a copy of the number for use in the final message
- int numSaved = num;
- while (num > 0)
- {
- //use mod operator (%) to get the last digit
- //eg: 567 % 10 gives a 7, since 567 / 10 is 56 with remainder 7.
- lastDigit = num % 10;
- //Add the digit to the running total
- total = total + lastDigit;
- //Chop off the last digit, now that we're done with it
- //Divide by 10, but stored in an integer just drops the last digit
- //eg: 567 / 10 = 56.7 but as int its just stored as 56. The 7 is now gone.
- num = num / 10;
- }
- printf("The digits of %i add up to %i\n", numSaved, total);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement