How to write a C Program to Check for Prime Armstrong or Perfect Number with an example?.
We already explained the concept of Prime, Armstrong, or Perfect Number in our previous articles. So, I suggest you refer C Program for Armstrong Number, C Program to find the Perfect Number and C program to find Prime Number articles in C Programming to understand the code.
C Program to Check for Prime Armstrong or Perfect Number
This program to check prime, Armstrong, or perfect number allows the user to enter the Size and the row elements of One Dimensional Array. Next, we created an individual function to find whether it is a Prime Number, Armstrong Number, or Perfect Number.
/* C Program to Check for Prime Armstrong or Perfect Number */ #include <stdio.h> #include <math.h> int Check_Armstrong (int Number); int Perfect_Number(int Number); int Prime_Number(int Number); int main() { int Number; printf("\nPlease Enter Number to Check whether it is an Armstrong, Prime, or Perfect : "); scanf("%d", &Number); // Calling Check_Armstrong Function to Check whether it is an Armstrong Number or Not if (Check_Armstrong(Number)) printf("\n %d is an Armstrong Number.", Number); else printf("\n %d is not an Armstrong Number.", Number); // Calling Prime_Number Function to Check whether it is a Prime Number or Not if(Prime_Number(Number) ) printf("\n %d is a Prime Number", Number); else printf("\n %d is Not a Prime Number", Number); // Calling Perfect_Number Function to Check whether it is a Perfect Number or Not if (Perfect_Number(Number) ) printf("\n %d is a Perfect Number", Number) ; else printf("\n %d is not a Perfect Number", Number) ; return 0; } /* C Program for Armstrong Number */ int Check_Armstrong (int Number) { int Temp, Reminder, Times = 0, Sum = 0; Temp = Number; while (Temp != 0) { Times = Times + 1; Temp = Temp / 10; } for(Temp = Number; Temp > 0; Temp = Temp /10 ) { Reminder = Temp % 10; Sum = Sum + pow(Reminder, Times); } if ( Number == Sum ) return 1; else return 0; } /* C Program for Perfect Number */ int Perfect_Number(int Number) { int i, Sum = 0 ; for(i = 1 ; i < Number ; i++) { if(Number % i == 0) Sum = Sum + i ; } if (Sum == Number) return 1; else return 0; } /* C Program to Find Prime Number */ int Prime_Number(int Number) { int i, Count = 0; for (i = 2; i <= Number/2; i++) { if(Number%i == 0) { Count++; } } if(Count == 0 && Number != 1 ) return 1; else return 0; }
2nd OUTPUT
Please Enter Number to Check whether it is an Armstrong, Prime, or Perfect : 2
2 is an Armstrong Number.
2 is a Prime Number
2 is not a Perfect Number
OUTPUT 3
Please Enter Number to Check whether it is an Armstrong, Prime, or Perfect : 6
6 is an Armstrong Number.
6 is Not a Prime Number
6 is a Perfect Number