Modulus operator (%) comes in handy in this challenge. So how does it help? When you do a number % 10, it gives the unit's digit of the number(Why?). Then, dividing the number by 10, will eliminate the unit's digit in the number. Using a do..while loop, we can solve this challenge.
A do..while loop executes at least once, because the statements in the do part of the loop are executed at least once, after which the condition in the while is checked.
What would be the condition in the while loop? Well, we want to find the sum of all the digits of the given number, so the condition in the while statement would be number != 0, which means, we need to keep executing the statements do, while the number is not equal to 0. Look at the code below to see how to solve this challenge.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
int sum = 0;
do {
sum += (n % 10);
n /= 10;
}
while(n != 0);
printf("%d", sum);
return 0;
}
Sum of Digits of a Five Digit Number in C – Hacker Rank Solution
ReplyDeletehttps://www.codeworld19.com/sum-of-digits-of-a-five-digit-number-in-c-hacker-rank-solution/