Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check if a number is Harshad Number or not

C++ Numbers: Exercise-20 with Solution

Write a program in C++ to check if a number is Harshad Number or not.

Sample Solution:

C++ Code :

#include<bits/stdc++.h>
using namespace std;
bool chkHarshad(int n)
{
    int s = 0;
	int tmp;
    for (tmp=n; tmp>0; tmp /= 10)
        s += tmp % 10;
    return (n%s == 0);
}
 

int main()
{
    int hdno;
 cout << "\n\n Check whether a number is Harshad Number or not: \n";
 cout << " ---------------------------------------------------\n";
 cout << " Input a number: ";
 cin >> hdno;
 
     if( chkHarshad(hdno))
        cout << " The given number is a Harshad Number."<<endl;
    else
        cout << " The given number is not a Harshad Number."<<endl;
    return 0;

}

Sample Output:

Check whether a number is Harshad Number or not:                                                    
 ---------------------------------------------------                                                 
 Input a number: 18                                                                                  
 The given number is a Harshad Number.

Flowchart:

Flowchart: Check if a number is Harshad Number or not
Flowchart: Check if a number is Harshad Number or not

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find Disarium numbers between 1 to 1000.
Next: Write a program in C++ to find Harshad Number between 1 to 100.

What is the difficulty level of this exercise?