In this tutorial we are going to solve the HackerRank Sum of Digits of a five-digit number problem or write a program for that. In this problem we need to take an input of a five-digit number that is always greater than 10000 and less than 99999. and on the output screen, we need to print the sum of that five-digit number.
Logic – How are we going to calculate the sum?
Let say we have a digit 45644 and if we module this number by 10 then we get the last digit of the number that 4 means 45644%10 then the remainder is 4. After the division by 10 45644/10 we get the remaining 4 digits 4564. we will use this logic five times and will sum the reminder and we will get the sum of 5 digit number. Similarly, we can apply this logic to any length of number.
![Sum of digits of five digits number solution](https://programmingoneonone.com/wp-content/uploads/2024/07/HackerRank-sum-of-digits-of-five-digits-number.webp)
Solution in C Programming
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
int digit, temp, sum = 0;
temp = n;
//Complete the code to calculate the sum of the five digits on n.
while(temp > 0)
{
digit = temp % 10;
sum = sum + digit;
temp = temp / 10;
}
printf("%d\n",sum);
return 0;
}