Print Sum of all digits in Numbers From 1 to N in Java

Modest programs can become severely difficult if the programmer itself does not understand the problem statement. So getting clarification of the problem statement is extremely necessary before you begin solving that problem. Now during competitions, interview rounds, etc, the problem statement itself is very confusing. One of the very simplest yet confusing problem statements we found is of performing addition. Well as simple as it sounds the complex it is. So today we’re going to find out how to Print Sum of all digits in Numbers From 1 to N in Java


What’s The Approach?


  • One of the simplest approaches we can use is to traverse all the numbers from 1 to N. And for each number we can compute the sum of its digits.


  • We will perform modulo operation x % 10 for each number from 1 to N so that we get individual digits of each number eventually added up in the sum variable.


  • After the above instruction gets executed successfully, we will do x = x / 10. So that we know when to stop.


  • The above instructions will keep executing till x != 0  remains true.


Also Read: How To Check If Two Strings Are Anagram using Java?


Java Program To Print Sum of All Digits in Numbers From 1 to N



n = 328




Sum of digits in numbers from 1 to 328 is 3241


// A Simple JAVA program to compute sum of
// digits in numbers from 1 to n

class TechDecodeTutorials {
    // Returns sum of all digits in numbers
    // from 1 to n
    static int sumOfDigitsFrom1ToN(int n)
        int result = 0; // initialize result
        // One by one compute sum of digits
        // in every number from 1 to n
        for (int x = 1; x <= n; x++)
            result += sumOfDigits(x);
        return result;
    // A utility function to compute sum
    // of digits in a given number x
    static int sumOfDigits(int x)
        int sum = 0;
        while (x != 0)
            sum += x % 10;
            x = x / 10;
        return sum;
    // Driver Program
    public static void main(String args[])
        int n = 328;
        System.out.println("Sum of digits in numbers"
                        +" from 1 to " + n + " is "
                        + sumOfDigitsFrom1ToN(n));



I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.