Sum of Digits of a Five Digit Number in C HackerRank Solution

Hello Programmers, In this post, you will know how to solve the Sum of Digits of a Five Digit Number in C HackerRank Solution. This problem is a part of the HackerRank C Programming Series.

Sum of Digits of a Five Digit Number in C HackerRank Solution
Sum of Digits of a Five Digit Number in C HackerRank Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

Sum of Digits of a Five Digit Number in C

Objective

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

Sum of Digits of a Five Digit Number in C Solution

#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 Problem (Sum of Digits of a Five Digit Number in C) is generated by Hackerrank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: Small Triangles, Large Triangles in C HackerRank Solution

Leave a Reply

Your email address will not be published. Required fields are marked *