Sum of Digits of a Five Digit Number || Hackerrank step by step solution

Sum of Digits of a Five Digit Number || Hackerrank step by step solution:


Welcome back, guys! So we will discuss Sum of Digits of a Five Digit Number Hackerrank Problem it's easy problem only knowledge of loops is required for it along with how to extract digits from a number.



Problem Statement of  Sum of Digits of a Five Digit Number:

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 the first digit of a number we divide the given number by 10  until the number is greater than 10. In 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 for  Sum of Digits of a Five Digit Number :

The 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. I will provide a solution using each loop.

Using For Loop:

#include<stdio.h>
int main()
{
    int i=0,n=0,sum=0;
    scanf("%d",&n);
    for(i=n;i>0;i =i/10)
    {     sum +=i%10;
    }
    printf("%d",sum);
    return 0;
}

Using While Loop:

#include<stdio.h>
int main()
{
    int n=0,sum=0;
    scanf("%d",&n);
   while(n>0)
{
        sum += n%10;
        n = n/10;
    }
    printf("%d",sum);
    return 0;
}

Using DO WHILE Loop:

#include<stdio.h>
int main()
{
    int n=0,sum=0;
    scanf("%d",&n);
   #include<stdio.h>
int main()
{
    int n=0,sum=0;
    scanf("%d",&n);
   do{
        sum += n%10;
        n = n/10;
    }while(n>0);
    printf("%d",sum);
    return 0;
}
    printf("%d",sum);
    return 0;
}
Analysis the code properly.
Feel free to ask your doubts in comments down below.
Please like share and subscribe to my YouTube Channel.
See you Next time.





Post a Comment

1 Comments