# C Program to Check Whether a Number is a Harshad Number or Not

Hey folks, today you will learn how to check whether a number is a Harshad number or not in the C programming language.

If a number is divisible by the sum of its digits, then that number is a Harshad Number. For example, 144 is a Harshad number because 1 + 4 + 4 = 9, and 144 is divisible by 9. Some other examples of Harshad numbers are 18, 27, 54, 156, 1729, and so on.

A Harshad number is also called a ‘Niven Number’.

The below program prompts the user to enter a number, then it displays the message whether the entered number is a Harshad number or not.

## C Program to Check Whether a Number is a Harshad Number or Not

C Program

```// C Program to Check Whether a Number is Harshad Number or Not
#include <stdio.h>

int main()
{
int num, n, rem = 0, sum = 0;

printf("Enter a number to check: ");
scanf("%d", &num);

n = num;

// Calculating the sum
while (num > 0)
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}

// Check whether number is equal to the sum
if (n % sum == 0)
{
printf("%d is a harshad number.", n);
}
else
{
printf("%d is not a harshad number.", n);
}

return 0;
}```

Output 1

Output 2

## How Does This Program Work?

```    int num, n, rem = 0, sum = 0;
```

In this program, we have declared four int data type variables named `num`, `n`, `rem`, and `sum`.

```    printf("Enter a number to check: ");
scanf("%d", &num);
```

Then, the program prompts the user to enter a number. The `scanf()` function is used to read the number entered by the user and store it in the `num` variable.

```    n = num;
```

We store the value of the original number in the `n` variable to use it later in the comparison.

```    while (num > 0)
{
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
```

Then, we use a loop to calculate the sum of digits of the entered number. Suppose the user entered the number 45, then:

The sum will be 9.

Now, we check whether the original number is divisible by the sum of digits or not.

```    if (n % sum == 0)
{
printf("%d is a harshad number.", n);
}
else
{
printf("%d is not a harshad number.", n);
}```
• If the original number is completely divisible by the sum of digits of the original number, then that number is a Harshad number.
• If the original number is not completely divisible by the sum of digits, then the entered number is not a Harshad number.

## Conclusion

I hope after going through this tutorial, you understand how to check whether a number is a Harshad number or not using the C programming language.

You can use the same logic to check for Harshad number in other programming languages.