Wednesday, January 8, 2020

Sum of Digits of a Five Digit Number - Hacker Rank Solution

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.


Sum of Digits of a Five Digit Number - Hacker Rank Solution


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;
}

1 comment:

Powered by Blogger.