Whether a number is Harshad number (niven) or not in C++

In this tutorial, we are going to learn how to check if a number is a Harshad number (Niven number ) or not in C++ with a simple and easy program.

Harshad or Niven number in C++

Any decimal number in which sum of its digits can divide the given number is called Harshad or Niven number.

For eg. 18= 1+8=9; 9 divides 18. Hence, 18 is a Harshad number. All single-digit number is Harshad.

Few mode harshad numbers: 1,2,3,4,5,6,7,8,9,10,12,18,20,…….

Approach to code:

  • break the number into digits using mod operation.
  • add the digits until reaching its unit place.
  • check if the sum of digits divides the given number and leaves remainder 0.
  • print “Yes” if we get our desired output else “No”

Check if a number is Harshad or Not in C++

//To check if the number is harshad(niven) or not 
{ int n,m,a;                 //initializing the variables
 int sum=0; 
cin>>n;                      //enter the number
 m=n;                        // storing value of n
 { a=n%10;         //spliting in digits
sum=sum+a; //getting sum of digits
 if((m%sum)==0) //checking condition
 cout<<"Yes the number is niven"; 
cout<<"No number is not niven"; 
} // end of main
Input 1:

Yes the number is niven

Input 2 :

No number is not niven

For any doubts please comment below we will try to reply and clear it soon. Thanks!


Decimal to Octal conversion in C++

 reverse pattern of digits using C++

Print all the Repeated Numbers with Frequency in an Array in C++

Stack in C++ Standard Template Library (STL)

Leave a Reply

Your email address will not be published. Required fields are marked *