Instagram
youtube
Facebook
Twitter

Sum of Digits of a Five Digit Number HackerRank Solution

Objective

The modulo operator, %, returns the remainder of a division. For example, 4 % 3 = 1 and 12 % 10 = 2. The ordinary division operator, /, returns a truncated integer value when performed on integers. For example, 5 / 3 = 1. To get the last digit of a number in base 10, use 10 as the modulo divisor.

Task

Given a five digit integer, print the sum of its digits.

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:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
	
    int num, sum = 0;
    scanf("%d", &num);
    while(num != 0) {
        sum += num % 10;
        num /= 10;
    }
    printf("%d", sum);
}

Steps Used in solving the problem -

  • Step 1: First, we imported the required header files.

  • Step 2: Then, we declared the main function and two integer variables inside it.

  • Step 3: Then, we used scanf function to read the user input and stored it in num variable.

  • Step 4: After this, we used a while loop that will execute as long as the value of num is not equal to 0. and, the next two lines of code are used to add the last digit to the sum and to remove last digit from the number.

  • Step 5: At last we used the "printf" function to print the result.