Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Iterative Constructs in Java

Chapter 9

Iterative Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Check Niven Number (Harshad Number)


24. Write a program to accept a number and check and display whether it is a Niven number or not. (Niven number number which is divisible by the sum of its digits).
Example:
Consider the number 126.
Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9.

Program Title: Check Niven Number

import java.util.Scanner;

 

public class NivenNumber {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter a number: ");

        int num = sc.nextInt();

        int temp = num;

 

        int sum = 0;

 

        // Calculate sum of digits

        while (temp != 0) {

            int digit = temp % 10;

            sum += digit;

            temp /= 10;

        }

 

        System.out.println("Sum of digits: " + sum);

 

        // Check divisibility

        if (num % sum == 0) {

            System.out.println(num + " is a Niven Number.");

        } else {

            System.out.println(num + " is NOT a Niven Number.");

        }

 

        sc.close();

    }

}

Output

Sample Input / Output 1:
Enter a number: 126
Sum of digits: 9
126 is a Niven Number.

Sample Input / Output 2:
Enter a number: 123
Sum of digits: 6
123 is NOT a Niven Number.

📝 Explanation

  1. Niven Number: A number divisible by the sum of its digits.
  2. num % sum_of_digits == 0
  3. Extract digits using % 10 and sum them.
  4. Check if num is divisible by sum.
  5. Display result.