DEV Community

Cover image for CodeChef - Sum Of Digits Of a Number
Atharva Siddhabhatti
Atharva Siddhabhatti

Posted on

CodeChef - Sum Of Digits Of a Number

Problem Code:- FLOW006

Problem Statement:- You're given an integer N. Write a program to calculate the sum of all the digits of N.

Input

The first line contains an integer T, the total number of testcases. Then follow T lines, each line contains an integer N.

Output

For each test case, calculate the sum of digits of N, and display it in a new line.

Explanation

As said in the problem statement, we have to find the sum of all the digits of a number. For Example:- 321 will be 3+2+1 = 6.

For this we use basic math rule which is of division when we do the 10 modulo of any number we get the last digit of that number as the output, using this principle we get the last digit of 321 number which is 1. After that we divide n by 10 which will be 321/10 = 32.1 but as we have declared n as integer the value taken by the complier will be 32 and we save 32 in n. After that we repeat the above steps until the value of n becomes 0 and in last we print the sum. The below code explains it.

In each program we take T as a Test cases so that we can supply multiple input to the program in a single run and get the output for all of them in one step rather than running the program multiple times for each input. Basic for loop is used for this purpose.

while(n!=0) {
            sum = sum+n%10;
            n=n/10;
        }
        System.out.println(sum);
Enter fullscreen mode Exit fullscreen mode

Input:

3
321
4252
1556434
Enter fullscreen mode Exit fullscreen mode

Output:

6
13
28
Enter fullscreen mode Exit fullscreen mode

Link to original problem https://www.codechef.com/problems/FLOW006

Run the program from here:- Click Here

Add input in Stdin Inputs

LIKE! SHARE! COMMENT!

Top comments (0)