Sum of Digits of a Five Digit Number in C - Hacker Rank Solution
Problem
Objectives
In order to get the last digit of a number, we use modulo operator \%. When the number is modulo divided by 10 we get the last digit.
To find first digit of a number we divide the given number by 10 until number is greater than 10. At the end we are left with the first digit.
Task
In this challenge, you have to input a five digit number and print the sum of digits of the number.Input Format
The input contains a single five digit number, n.Constraints
- 10000 <= n <= 99999
Output Format
Print the sum of the digits of the five digit number.
Sample Input 0
10564
Sample Output 0
16
Solution :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n,last_num,sum = 0,temp; scanf("%d", &n); temp = n; while(temp > 0) { last_num = temp %10; sum = sum + last_num; temp = temp/10; } printf("%d",sum); return 0; } |
Disclaimer :-
the above whole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.
int main() {
int n, i,sum;
int value=0;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
for(i=0;i<5;i++)
{
sum=n%10;
value=value+sum;
n=n/10;
}
printf("%d",value);
return 0;
}
compiled successful, but 7/7 test case failed why?
Pls share ur complete code...
What's i here?
i is a variable which store the value of integer type.
value unselected..
value undelecred
Firstly check I already declared the value .
why we are using sum=n%10; can u plz tell me logic behind it .
if you are try to %10 operation on any number it will always return the last digit of that number
for examle..
545%10 then the result is 5, the last digit of 545 is 5.
compiled successful but 7/7 test case failed , whats wrong with this code (:
int main() {
int n,rem[5],i,sum=0;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
for(i=1;i<=5;i++)
{
rem[i]=n%10;
n=n/10;
sum=sum+rem[i];
}
printf("%d",sum);
return 0;
}