Here's a C program that checks whether a number is prime or an Armstrong number using user-defined functions. In this program, we define two functions: one to check for prime numbers and another to check for Armstrong numbers. Armstrong numbers are also known as narcissistic numbers, and they are numbers for which the sum of their own digits, each raised to the power of the number of digits, is equal to the number itself.
#include <stdio.h>
#include <math.h>
// Function to check if a number is prime
int isPrime(int num) {
if (num <= 1) {
return 0; // 0 and 1 are not prime numbers
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return 0; // If divisible by any number between 2 and sqrt(num), it's not prime
}
}
return 1; // It's a prime number
}
// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
int originalNum, remainder, result = 0, n = 0;
originalNum = num;
while (originalNum != 0) {
originalNum /= 10;
++n;
}
originalNum = num;
while (originalNum != 0) {
remainder = originalNum % 10;
result += pow(remainder, n);
originalNum /= 10;
}
if (result == num)
return 1; // It's an Armstrong number
else
return 0; // It's not an Armstrong number
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (isPrime(num)) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
if (isArmstrong(num)) {
printf("%d is an Armstrong number.\n", num);
} else {
printf("%d is not an Armstrong number.\n", num);
}
return 0;
}
When you run this program, it will first ask you to enter a number. Then it will use the isPrime
and isArmstrong
functions to check if the number is prime and/or an Armstrong number and display the appropriate messages. Here's how the output may look for different inputs:
Example 1 (Prime and Armstrong):
Enter a number: 153
153 is not a prime number.
153 is an Armstrong number.
Example 2 (Prime but not Armstrong):
Enter a number: 13
13 is a prime number.
13 is not an Armstrong number.
Example 3 (Neither Prime nor Armstrong):
Enter a number: 20
20 is not a prime number.
20 is not an Armstrong number.
Example 4 (Neither Prime nor Armstrong):
Enter a number: 0
0 is not a prime number.
0 is not an Armstrong number.
Please note that 0 and 1 are not considered prime numbers.