Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

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 + 3= 9

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

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

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

C++ Code:-

   
    //C++ Program
    //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: 81
    81 is a harshad number