KnowledgeBoat Logo

Computer Applications

Write a program to input a number and check whether it is a Harshad Number or not. [A number is said to be Harshad number, if it is divisible by the sum of its digits. The program displays the message accordingly.]
For example;
Sample Input: 132
Sum of digits = 6 and 132 is divisible by 6.
Output: It is a Harshad Number.
Sample Input: 353
Output: It is not a Harshad Number.

Java

Java Iterative Stmts

27 Likes

Answer

import java.util.*;

public class KboatHarshadNumber
{
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = in.nextInt();
        int x = num, rem = 0, sum = 0;
         
        while(x > 0) {
            rem = x % 10;
            sum = sum + rem;
            x = x / 10;
        }
        
        int r = num % sum;
         
        if(r == 0)
            System.out.println(num + " is a Harshad Number.");
        else
            System.out.println(num + " is not a Harshad Number.");      
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input a number and check whether it is a Harshad Number or not. [A number is said to be Harshad number, if it is divisible by the sum of its digits. The program displays the message accordingly.] For example; Sample Input: 132 Sum of digits = 6 and 132 is divisible by 6. Output: It is a Harshad Number. Sample Input: 353 Output: It is not a Harshad Number.

Answered By

14 Likes


Related Questions