Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Sum of Digits (Recursive) (OOP)

Updated 20 Oct 2026

This program finds the sum of the digits of a number with a recursive method, using a class whose constructor stores the number. The method findSum() adds the last digit (% 10) to the sum of the remaining digits (/ 10), calling itself until no digits are left.

Definition

The sum of digits of a number is the total of its digits. For example $90507$: $9 + 0 + 5 + 0 + 7 = 21$. The last digit is k % 10 and the rest of the number is k / 10.

A recursive method needs a base case (stops without calling itself) and a recursive case (calls itself with a smaller problem).

A negative number is rejected with an error message; only 0 or a positive number is accepted.

Algorithm

  1. Start. In main(), read the number x with a Scanner.
  2. Create the object ob with new DigitSum(x). The constructor copies the number into the data member num and sets total to 0.
  3. Call isValid(). It returns true only if num is 0 or more; otherwise print an error message and stop.
  4. Call compute(), which calls findSum(num) and stores the value in total. Inside findSum(k):
    • Base case: if k == 0, return 0.
    • Recursive case: otherwise return k % 10 + findSum(k / 10). Each call removes one digit.
  5. Call show() to print the sum.
  6. Stop.

For 0 the answer is 0 because the base case returns 0 at once.

Program

The constructor DigitSum() stores the number, isValid() checks it, findSum() is recursive, compute() stores its value and show() prints it.

import java.util.*;
/** Class DigitSum: stores a number and finds the sum of its digits using recursion. */
class DigitSum
{
    int num;    // the number whose digits are added
    int total;  // sum of the digits of num

    /** Constructor: stores the given number and sets total to 0. */
    DigitSum(int x)
    {
        num = x;
        total = 0;
    }

    /** Returns true if num is 0 or more. */
    boolean isValid()
    {
        return num >= 0;
    }

    /**
     * Recursive method: returns the sum of the digits of k.
     * k: the number for this call (k >= 0)
     */
    int findSum(int k)
    {
        if (k == 0)                        // base case: no digits left
            return 0;
        return k % 10 + findSum(k / 10);   // recursive case: last digit + sum of the rest
    }

    /** Calls findSum() with the stored number and keeps the value in total. */
    void compute()
    {
        total = findSum(num);
    }

    /** Shows the sum. */
    void show()
    {
        System.out.println("Sum of the digits of " + num + " = " + total);
    }

    /** main: reads the number, creates the object and calls the methods. */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number (0 or more): ");
        int x = sc.nextInt();
        DigitSum ob = new DigitSum(x);   // object created with the constructor
        if (ob.isValid())
        {
            ob.compute();
            ob.show();
        }
        else
            System.out.println("Invalid input: enter 0 or a positive number");
    }
}

Variable description table

VariableData TypePurpose
numintData member: the number whose digits are added
totalintData member: stores the sum of the digits of num
xintConstructor parameter in DigitSum(): the number received; also the local variable in main() holding the number typed by the user
kintParameter of findSum(): the number of this call, divided by 10 in each recursive call
scScannerObject used in main() to read the number
argsString[]Command line arguments of main() (not used)
obDigitSumObject of the class created in main()

Sample input and output

Sample 1

Enter a number (0 or more): 90507
Sum of the digits of 90507 = 21

Sample 2

Enter a number (0 or more): 0
Sum of the digits of 0 = 0

Sample 3

Enter a number (0 or more): -45
Invalid input: enter 0 or a positive number

One value per line

Dry run

Take $90507$. The constructor sets num = 90507. compute() calls findSum(90507).

Callkk % 10ActionValue returned
findSum(90507)9050777 + findSum(9050), waits21
findSum(9050)905000 + findSum(905), waits14
findSum(905)90555 + findSum(90), waits14
findSum(90)9000 + findSum(9), waits9
findSum(9)999 + findSum(0), waits9
findSum(0)0-base case0

Returning up: 0, then 9 + 0 = 9, 0 + 9 = 9, 5 + 9 = 14, 0 + 14 = 14, 7 + 14 = 21. total becomes 21 and show() prints Sum of the digits of 90507 = 21, the same as the first sample run.

Variations

  1. Sum of digits using a loop "Write a program to find the sum of the digits of a number using a loop."
  2. Reverse a number "Using recursive technique, find the reverse of a number."
  3. Repeated addition "Keep adding the digits of a number until a single digit is left."