Dremendo Tag Line

Input a number and check if it is a Niven (Harshad) number or not using a function in Java

Function - Question 9

In this question, we will see how to input a number and check if it is a Niven (Harshad) number or not in Java programming using a function. To know more about function click on the function lesson.

Q9) Write a program in Java to input a number and check if it is a Niven (Harshad) number or not using a function. The function should return 1 if the numbers is a Niven number else return 0.

A Niven number is an integer number that is divisible by the sum of its digits.

Example: 18 is a Niven number because the sum of its digit is 9 and 18 is divisible by 9.

Program

import java.util.Scanner;

public class Q9
{
    public static int niven(int num)
    {
        int s=0,t,d;
        t=num;

        while(t>0)
        {
            d=t%10;
            s=s+d;     // sum of the digits
            t=t/10;
        }

        if(num%s==0)
        {
            return 1;
        }
        return 0;
    }

    public static void main(String args[])
    {
        int n;
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a numbers ");
        n=sc.nextInt();

        if(niven(n)==1)
        {
            System.out.print("Niven Number");
        }
        else
        {
            System.out.print("Not Niven Number");
        }
    }
}

Output

Enter a number 18
Niven Number
video-poster