Niven (Harshad) Number Program in Java for ICSE Class 10

⚡ Direct Answer & Key Takeaway

A Niven (or Harshad) number is a positive integer n divisible by the sum of its decimal digits S(n), satisfying n % S(n) == 0. For instance, 156 has digit sum 1 + 5 + 6 = 12, and 156 % 12 == 0, making it a Niven number. In Java BlueJ, copy input num into temp, extract digits with temp % 10 inside a while (temp > 0) loop, accumulate sum, and verify num > 0 && num % sum == 0 to avoid division by zero.

1. Mathematical Rule Behind Harshad Numbers

Divisibility by one's own digit sum defines the Niven number family in base-10 arithmetic. Formally, any positive integer n is called a Niven or Harshad number if S(n) divides n with zero remainder, where S(n) represents the sum of all decimal digits of n. For example, 18 yields S(18) = 1 + 8 = 9, and since 18 / 9 = 2 with remainder 0, 18 qualifies. Conversely, 19 yields S(19) = 10, which leaves remainder 9, disqualifying 19. In CISCE ICSE Class 10 Computer Applications papers, Niven checks often appear as standalone Section B programs or as one branch inside a menu-driven switch-case question alongside Spy or Automorphic numbers. Recognizing the exact mathematical boundary—only strictly positive integers are valid candidates—ensures you handle invalid zero or negative inputs cleanly before entering the summation loop.

  • All integers from 1 through 9 are Niven numbers because n % n == 0.
  • Base-10 Harshad numbers are tested using integer division (/) and modulus (%) rather than floating-point math.
  • Zero is excluded because division by S(0) = 0 is mathematically undefined.

2. Digit Extraction Loop and Zero-Sum Guard

Extracting digits from right to left in Java relies on pairing the modulus operator (%) with integer division (/). Inside `while (temp > 0)`, the expression `temp % 10` isolates the units digit, which is added to `sum`, and `temp / 10` truncates that units digit for the next iteration. Preserving the original input in `num` while mutating `temp` is essential because `num` is needed after the loop ends for the final `num % sum == 0` check. Notice the early validation block `if (num <= 0)` placed before the loop: if a student enters 0, `while (temp > 0)` never executes, leaving `sum = 0`, which would trigger `ArithmeticException: / by zero` at `num % sum`. Rejecting non-positive numbers upfront guarantees safe execution across every test case.

  • Always copy `num` into `temp` before starting the digit-extraction loop.
  • Initialize `sum = 0` before the loop so each run starts from a clean accumulator.
  • Guard against `num <= 0` to prevent `ArithmeticException` on `num % sum`.

3. Step-by-Step Dry Run for Input 156

Tracing the loop step by step on `num = 156` shows exactly how variables evolve in BlueJ memory. Initially, `num = 156`, `temp = 156`, `sum = 0`, and `digit = 0`. In Iteration 1 (`156 > 0`), `digit = 156 % 10 = 6`, `sum = 0 + 6 = 6`, and `temp = 156 / 10 = 15`. In Iteration 2 (`15 > 0`), `digit = 15 % 10 = 5`, `sum = 6 + 5 = 11`, and `temp = 15 / 10 = 1`. In Iteration 3 (`1 > 0`), `digit = 1 % 10 = 1`, `sum = 11 + 1 = 12`, and `temp = 1 / 10 = 0`. Now `temp > 0` evaluates to `false`, terminating the loop. Finally, `156 % 12 == 0` evaluates to `true`, confirming 156 is a Niven number. Testing a non-Niven trace such as `124` gives `sum = 7` and `124 % 7 = 5 != 0`, printing the negative result.

  • Iteration 1 (temp=156): digit=6, sum=6, next temp=15.
  • Iteration 2 (temp=15): digit=5, sum=11, next temp=1.
  • Iteration 3 (temp=1): digit=1, sum=12, next temp=0 (loop ends; 156 % 12 == 0).

4. NivenNumber.java (ICSE BlueJ Program)

import java.util.Scanner;

public class NivenNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int num = sc.nextInt();

        if (num <= 0) {
            System.out.println(num + " is NOT a Niven (Harshad) number.");
            sc.close();
            return;
        }

        int temp = num;
        int sum = 0;
        int digit = 0;

        while (temp > 0) {
            digit = temp % 10;
            sum = sum + digit;
            temp = temp / 10;
        }

        if (num % sum == 0) {
            System.out.println(num + " is a Niven (Harshad) number (Digit Sum = " + sum + ").");
        } else {
            System.out.println(num + " is NOT a Niven (Harshad) number (Digit Sum = " + sum + ").");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a positive integer: 156
156 is a Niven (Harshad) number (Digit Sum = 12).

Enter a positive integer: 124
124 is NOT a Niven (Harshad) number (Digit Sum = 7).

5. Variable Description Table (VDT)

Variable NameData TypePurpose in Program
scScannerReads the integer input from the user via standard input
numintStores the original input integer preserved for final divisibility testing
tempintHolds a mutable copy of num reduced by dividing by 10 in each iteration
digitintCaptures the rightmost extracted digit (temp % 10) during each pass
sumintAccumulates the sum of all extracted digits of the number
🎯 1-on-1 Live Mentorship & Free Study Kit

Master ICSE Java Loops With 1-on-1 Guided Coding Practice

Practice BlueJ number programs, dry-run tracing, and VDT writing with IIT/NIT mentors at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods).

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Destroying the original num inside the while loop instead of copying it into temp, which causes num % sum == 0 to evaluate 0 % sum == 0 and falsely print Niven for every input.
  • Avoid Mistake: Skipping the num <= 0 check before dividing by sum; entering 0 makes sum equal to 0 and crashes the program with ArithmeticException: / by zero.
  • Avoid Mistake: Using float or double division instead of the integer modulus operator (%), introducing unnecessary type-casting errors in board answer scripts.
  • Examiner / Mentor Tip: CISCE examiners deduct marks if you skip the Variable Description Table (VDT); list every primitive variable and Scanner object with exact Java data types.
  • Examiner / Mentor Tip: Write clear user prompts using System.out.print and close the Scanner object with sc.close() to show disciplined resource handling.
  • Examiner / Mentor Tip: When asked in viva why temp is used, explain that num must remain unchanged for the post-loop divisibility test num % sum == 0.

7. Interactive Concept Check Quiz

Question: Which of the following integers is NOT a Niven (Harshad) number?

8. Frequently Asked Questions

Is there any difference between a Niven number and a Harshad number in ICSE exams?
Niven and Harshad refer to the exact same integer property. Indian mathematician D. R. Kaprekar coined "Harshad" (meaning joy-giver in Sanskrit), while Ivan Niven popularized the concept in a 1977 lecture; CISCE ICSE question papers use both terms interchangeably.
Are all single-digit positive integers Niven numbers?
Every single-digit positive integer from 1 to 9 is automatically a Niven number because the digit sum equals the number itself, and every positive integer divides itself with zero remainder.
What happens if a user enters 0 or a negative number?
Zero has no positive digit sum, so evaluating 0 % 0 throws an ArithmeticException in Java. Always add an early guard rejecting inputs less than or equal to zero.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class