
Introduction
This program helps to check that entered number is Harshad Number or not. Before start writing code we have to understand Harshad Number and how it calculated.
Harshad Number is a positive integer which is divisible by the sum of its digits, it is also known as Niven number.
Note: Number should be greater than zero. like n>0
Example:
- The Number 18 is a Harshad Number because the sum of the digits 1 and 8 is 9 (1 + 8 = 9) and it is divisible by the sum of it’s digit. 18/(1+8)= 18/9 = 2
- The number 1729 is a Harshad number in base 10, because the sum of the digits 1 ,7, 2 and 9 is 19 (1 + 7 + 2 + 9 = 19), and 1729 is divisible by 19 (1729 = 19 * 91)
- The Number 31 is not a Harshad number in base 10, because the sum of the digits 3 and 1 is 4 (3+1 = 4), and 1729 is not divisible by 4.
Flowchart
Please find sample flowchart diagram for this program as given below –
Program(Code) Using Java Language
package com.kw.sample;
import java.util.Scanner;
/**
* This Program helps to check Number is Harshad Number or Not.
*
* For Example: 18 is a Harshad Number and 19 is not.
*
* @author dsahu1
*
*/
public class KWHarshadNumberExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int n = sc.nextInt();
int c = n, d, sum = 0;
// finding sum of digits
while (c > 0) {
d = c % 10;
sum = sum + d;
c = c / 10;
}
if (n % sum == 0) {
System.out.println(n + " is a Harshad Number.");
} else {
System.out.println(n + " is not a Harshad Number.");
}
}
}
Output
Scenario 1:
Enter a number : 10
10 is a Harshad Number.
Scenario 2:
Enter a number : 18
18 is a Harshad Number.
Video Explanation
This video helps to understand flowchart and program which written in the above steps. There are various ways to write a program and we are not covering all of them as this is just for practice. Please post your program in the comment box so other can utilize it.