#include <stdio.h>
// Function to calculate the sum of digits
int sumOfDigits(int number) {
int sum = 0;
while (number > 0) {
sum += number % 10; // Add the last digit
number /= 10; // Remove the last digit
}
return sum;
}
// Function to check if a number is a Harshad number
int isHarshad(int number) {
int sum = sumOfDigits(number);
return (sum != 0 && number % sum == 0); // Check divisibility
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
if (isHarshad(number)) {
printf("%d is a Harshad number.\n", number);
} else {
printf("%d is not a Harshad number.\n", number);
}
return 0;
}
Explanation:
sumOfDigits Function: This function calculates the sum of the digits of the given number.
isHarshad Function: This function checks if the number is divisible by the sum of its digits. It also ensures that the sum is not zero (to avoid division by zero).
main Function: This is the entry point of the program. It prompts the user to enter a number and uses the isHarshad function to determine if it’s a Harshad number.
Output of the Given Code:
Enter a number: 18
18 is a Harshad number.
Enter a number: 19
19 is not a Harshad number.