Unleashing the Power of C Programming: A Deeper Dive into User-Defined Functions
The Problem Statement
Given a number, how can we determine if it’s prime and Armstrong? A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. An Armstrong number, on the other hand, is a number that is equal to the sum of its own digits each raised to the power of the number of digits.
The Solution: User-Defined Functions to the Rescue
To tackle this problem, we’ll create two user-defined functions: checkPrimeNumber()
and checkArmstrongNumber()
. These functions will take an integer as input and return 1 if the number meets the respective criteria, and 0 otherwise.
Function Breakdown
Let’s dissect the checkPrimeNumber()
function:
int checkPrimeNumber(int num) {
int flag = 1;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
flag = 0;
break;
}
}
return flag;
}
The checkArmstrongNumber()
function follows a similar structure:
int checkArmstrongNumber(int num) {
int sum = 0, temp = num;
int digits = 0;
while (temp!= 0) {
digits++;
temp /= 10;
}
temp = num;
while (temp!= 0) {
int digit = temp % 10;
sum += pow(digit, digits);
temp /= 10;
}
return sum == num? 1 : 0;
}
Putting it all Together
In the main()
function, we prompt the user to enter a number:
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
int isPrime = checkPrimeNumber(num);
int isArmstrong = checkArmstrongNumber(num);
if (isPrime && isArmstrong) {
printf("%d is both prime and Armstrong.\n", num);
} else if (isPrime) {
printf("%d is prime but not Armstrong.\n", num);
} else if (isArmstrong) {
printf("%d is Armstrong but not prime.\n", num);
} else {
printf("%d is neither prime nor Armstrong.\n", num);
}
return 0;
}
The Power of User-Defined Functions
By creating these two functions, we’ve not only solved the problem but also demonstrated the flexibility and reusability of user-defined functions in C programming. By encapsulating complex logic within functions, we can write more efficient, modular, and maintainable code.
Some key benefits of using user-defined functions include:
- Modularity: Breaking down complex code into smaller, manageable functions makes it easier to understand and maintain.
- Reusability: Functions can be called multiple times within a program, reducing code duplication and increasing efficiency.
- Readability: Well-named functions and clear documentation make the code more readable and easier to understand.