C Program To Check Prime Or Armstrong Number Using User Defined Function
In C programming, user-defined functions are powerful tools for organizing code, promoting reusability, and enhancing readability. When tasked with checking specific properties of numbers, such as whether a number is prime or an Armstrong number, encapsulating the logic within functions makes your programs more modular and easier to maintain. In this article, you will learn how to write C programs using user-defined functions to determine if a given number is prime or an Armstrong number.
Problem Statement
Identifying specific types of numbers, like prime numbers (only divisible by 1 and themselves) or Armstrong numbers (equal to the sum of their digits each raised to the power of the number of digits), is a common task in programming. Without functions, repeated checks would lead to duplicated code blocks, making the program longer, harder to debug, and less efficient. The challenge is to implement these checks robustly and elegantly using modular functions.
Example
Consider checking the number 153 for both properties:
Input: 153
Expected Output: 153 is not a Prime number. 153 is an Armstrong number.
Background & Knowledge Prerequisites
To effectively follow this tutorial, readers should have a basic understanding of:
- Basic C Syntax: Variables, data types, operators (arithmetic, relational, logical).
- Control Flow Statements:
if-elseconditionals and looping constructs (for,while). - Functions: How to declare, define, and call functions, including understanding parameters and return types.
- Mathematical Concepts: Modulus operator (
%) for finding remainders and integer division (/) for digit extraction.
Use Cases or Case Studies
User-defined functions for number property checks have various applications:
- Number Theory Research: Exploring properties of numbers, generating lists of primes, or verifying Armstrong numbers within a range.
- Educational Software: Building interactive tools that help students understand number theory concepts by allowing them to test numbers.
- Algorithmic Challenges: Solving competitive programming problems that frequently involve identifying specific number types as part of a larger algorithm.
- Data Validation: In certain applications, input data might need to conform to specific numeric properties before further processing.
- Encryption and Security: Prime numbers, in particular, are fundamental to many cryptographic algorithms like RSA, where large prime numbers are essential components.
Solution Approaches
We will develop two primary functions: one to check for prime numbers and another for Armstrong numbers. Then, we will integrate them into a main function to demonstrate their usage.
Approach 1: Checking for Prime Number
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
- One-line summary: This approach uses a function to determine if a given integer is a prime number by checking for divisibility from 2 up to the square root of the number.
// Check Prime Number
#include <stdio.h>
#include <math.h> // Required for sqrt()
// Function to check if a number is prime
int isPrime(int num) {
// Step 1: Handle base cases for numbers less than or equal to 1
if (num <= 1) {
return 0; // Not prime
}
// Step 2: Loop from 2 up to the square root of the number
// If any number divides 'num' evenly, it's not prime
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; // Not prime
}
}
// Step 3: If no divisors found, the number is prime
return 1; // Prime
}
int main() {
int number = 7; // Example number
if (isPrime(number)) {
printf("%d is a Prime number.\\n", number);
} else {
printf("%d is not a Prime number.\\n", number);
}
number = 10; // Another example
if (isPrime(number)) {
printf("%d is a Prime number.\\n", number);
} else {
printf("%d is not a Prime number.\\n", number);
}
return 0;
}
Sample Output:
7 is a Prime number.
10 is not a Prime number.
Stepwise Explanation:
isPrime(int num)function:
- Takes an integer
numas input. - Base Cases: If
numis less than or equal to 1, it's immediately returned as not prime (0). - Loop for Divisors: It iterates from
i = 2up to the square root ofnum. Checking beyond the square root is redundant because ifnumhas a divisord > sqrt(num), it must also have a divisornum/d < sqrt(num). - Divisibility Check: Inside the loop, it checks if
numis perfectly divisible byiusing the modulus operator (%). - Return Value: If a divisor is found,
0(false) is returned. If the loop completes without finding any divisors,1(true) is returned, indicating the number is prime.
main()function:
- Demonstrates calling
isPrimewith sample numbers and printing the results based on the function's return value.
Approach 2: Checking for Armstrong Number
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because $1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153$.
- One-line summary: This approach implements a function to check if a number is an Armstrong number by calculating the sum of its digits raised to the power of the number of digits and comparing it to the original number.
// Check Armstrong Number
#include <stdio.h>
#include <math.h> // Required for pow()
// Function to check if a number is an Armstrong number
int isArmstrong(int num) {
int originalNum, remainder, n = 0;
double result = 0.0;
// Step 1: Store the original number
originalNum = num;
// Step 2: Count the number of digits (n)
// For single digit numbers, the power is 1.
// For multi-digit numbers, count the digits
int tempNum = num;
while (tempNum != 0) {
tempNum /= 10;
n++;
}
// Handle case for 0 (0 is technically an Armstrong number)
if (num == 0) return 1;
// Special handling for n=0 (when num was 0), set to 1 for correct power calc
if (n == 0) n = 1;
// Step 3: Calculate the sum of nth powers of its digits
tempNum = num; // Reset tempNum to the original number for digit extraction
while (tempNum != 0) {
remainder = tempNum % 10; // Get the last digit
result += pow(remainder, n); // Add digit raised to the power of n
tempNum /= 10; // Remove the last digit
}
// Step 4: Compare the result with the original number
if ((int)result == originalNum) {
return 1; // Armstrong number
} else {
return 0; // Not an Armstrong number
}
}
int main() {
int number = 153; // Example number
if (isArmstrong(number)) {
printf("%d is an Armstrong number.\\n", number);
} else {
printf("%d is not an Armstrong number.\\n", number);
}
number = 123; // Another example
if (isArmstrong(number)) {
printf("%d is an Armstrong number.\\n", number);
} else {
printf("%d is not an Armstrong number.\\n", number);
}
return 0;
}
Sample Output:
153 is an Armstrong number.
123 is not an Armstrong number.
Stepwise Explanation:
isArmstrong(int num)function:
- Takes an integer
numas input. - Store Original:
originalNumstores the inputnumfor final comparison. - Count Digits: A
whileloop is used to count the number of digits (n) innum. This count determines the power to which each digit will be raised. - Calculate Sum of Powers: Another
whileloop extracts digits fromtempNum(which is reset tooriginalNum). -
remainder = tempNum % 10gets the last digit. -
result += pow(remainder, n)adds the current digit raised to the powerntoresult. -
tempNum /= 10removes the last digit. - Compare: Finally,
result(converted to an integer) is compared withoriginalNum. - Return Value: Returns
1if they are equal (Armstrong), otherwise0.
main()function:
- Demonstrates calling
isArmstrongwith sample numbers and printing the results.
Approach 3: Combining Both Checks in the Main Program
This approach integrates both isPrime and isArmstrong functions into a single main program to check both properties for a user-input number.
- One-line summary: This program prompts the user for an integer and then uses the previously defined
isPrimeandisArmstrongfunctions to report both properties of the number.
// Check Prime or Armstrong Number
#include <stdio.h>
#include <math.h> // Required for sqrt() and pow()
// Function to check if a number is prime (from Approach 1)
int isPrime(int num) {
if (num <= 1) {
return 0;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
// Function to check if a number is an Armstrong number (from Approach 2)
int isArmstrong(int num) {
int originalNum, remainder, n = 0;
double result = 0.0;
originalNum = num;
int tempNum = num;
if (num == 0) { // Handle 0 separately for digit count
n = 1;
} else {
while (tempNum != 0) {
tempNum /= 10;
n++;
}
}
tempNum = num; // Reset tempNum for sum of powers calculation
while (tempNum != 0) {
remainder = tempNum % 10;
result += pow(remainder, n);
tempNum /= 10;
}
if ((int)result == originalNum) {
return 1;
} else {
return 0;
}
}
int main() {
int number;
// Step 1: Prompt user for input
printf("Enter a positive integer: ");
scanf("%d", &number);
// Step 2: Check if the number is prime using the isPrime function
if (isPrime(number)) {
printf("%d is a Prime number.\\n", number);
} else {
printf("%d is not a Prime number.\\n", number);
}
// Step 3: Check if the number is an Armstrong number using the isArmstrong function
if (isArmstrong(number)) {
printf("%d is an Armstrong number.\\n", number);
} else {
printf("%d is not an Armstrong number.\\n", number);
}
return 0;
}
Sample Output (User enters 153):
Enter a positive integer: 153
153 is not a Prime number.
153 is an Armstrong number.
Sample Output (User enters 7):
Enter a positive integer: 7
7 is a Prime number.
7 is not an Armstrong number.
Stepwise Explanation:
- Include Headers:
stdio.hfor input/output andmath.hforsqrt()andpow(). - Function Definitions: The
isPrimeandisArmstrongfunctions are defined exactly as in the previous approaches. main()function:
- Declares an integer
number. - Prompts the user to enter a positive integer using
printfand reads the input usingscanf. - Calls
isPrime(number)and prints the appropriate message based on its return value. - Calls
isArmstrong(number)and prints the appropriate message based on its return value.
Conclusion
By leveraging user-defined functions in C, we can effectively check if a number is prime or an Armstrong number. This approach not only makes the code modular and reusable but also significantly improves its readability and maintainability. Each function focuses on a single task, leading to cleaner and more robust programs for numerical property checks.
Summary
- Prime Number: A natural number greater than 1 that has no positive divisors other than 1 and itself.
- Armstrong Number: A number that is equal to the sum of its own digits each raised to the power of the number of digits.
- User-Defined Functions: Encapsulate specific logic (e.g.,
isPrime,isArmstrong) into reusable blocks. - Benefits: Functions enhance code organization, reduce redundancy, and make programs easier to debug and extend.
- Implementation: Both checks involve mathematical operations (modulus, division, powers) and control flow structures (loops, conditionals) within their respective functions.