Input a number and check if it is a Niven (Harshad) number or not using a function in C++
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 C++ programming using a function. To know more about function click on the function lesson.
Q9) Write a program in C++ 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
#include <iostream>
#include <conio.h>
using namespace std;
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;
}
int main()
{
int n;
cout<<"Enter a number ";
cin>>n;
if(niven(n)==1)
{
cout<<"Niven Number";
}
else
{
cout<<"Not Niven Number";
}
return 0;
}
Output
Enter a number 18 Niven Number