Created
November 22, 2018 17:10
-
-
Save dbc2201/00731f36f684c1404e73135d799e4eb8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
int main(void) | |
{ | |
int number = 0; | |
int digit = 0; | |
int sum = 0; | |
printf("Enter the five digit number : "); | |
scanf("%d", &number); | |
while ( number > 0 ) | |
{ | |
digit = number % 10; | |
sum = sum + digit; | |
number = number / 10; | |
} | |
printf("The sum of the digits is %d", sum); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this code, we are trying to retrieve the sum of the digits of a number. Though we have been already told that the number is going to be 5 digits, the code works for the numbers that are not.
Explanation :
the code inputs an integer value in the integer variable
number
.This is the number that we have to calculate the sum of digits for. Let us assume the number was
12345
.So, what we have done is, we have taken the number and done
digit = number % 10
This will fetch the digit on the one's place.
In this case,
12345 % 10 = 5
Hence the value of the variable digit is right now
5
.sum = sum + digit
Now, we are storing the value of
digit
to a variablesum
.sum has the value 0, sum --> 0, sum = sum + digit will yield, sum --> 5
number = number / 10
We have updated the value of
number
after dividing it by 10.number --> 12345 / 10 = 1234
We will repeat all the above steps until the number is greater than 0
Dry Run :