C++ program to check whether a number is a Harshad Number or not

Program to check whether a number is a Harshad Number or not

A Harshad number is a positive integer which is divisible by the sum of the digits of the integer. It is also called the Niven number.

To find the Harshad number find and add the digits of the number. If the number is divisible by the sum then the number is a Harshad number else not a Harshad number.

For Example : 153

Sum of digits = 1 + 5 + 39

153 is divisible by 9 so 153 is a Harshad Number.

Harshad Number

Algorithm:-

  1. Take input from User
  2. Input is stored in an int type variable say num.
  3. Input is copied in another variable say save
  4. A loop is started
    1. Digits of the number is found
    2. each digit is added to sum( initial value 0).
    3. num is divided by 10 i.e value of num is changed in every cycle.
    4. loop runs until num is greater than 0.
  5. save is divided by sum
    1. if there is no remainder then the number is a Harshad number
    2. otherwise number is not a Harshad number
Harshad Number or Not
#include<iostream>
using namespace std;
//main program
int main () 
{

   int num, sum = 0;
   cout << "Enter number: ";
   //user input
   cin >> num;

   int n = num;
   //loop to calculate the sum of digits

   while (num > 0)
   {
       int rem = num % 10;
       sum = sum + rem;
       num = num / 10;
   }
  //checking for harshad number
  if (n % sum == 0)
  {
       cout << n << " is a harshad number";
  }

  else
  {
      cout << n << " is not a harshad number";
  }
  return 0;
}

Output

Enter number: 71
71 is not a harshad number