In this example, two user-defined functions checkPrimeNumber()
and checkArmstrongNumber()
are created.
The checkPrimeNumber()
returns 1 if the number entered by the user is a prime number.
Similarly, checkArmstrongNumber()
returns 1 if the number entered by the user is an Armstrong number.
C++ Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #include <stdio.h> #include <iostream> #include <math.h> using namespace std; int checkPrimeNumber(int n) { int i, flag = 1; for(i=2; i<=n/2; ++i) { // condition for non-prime number if(n%i == 0) { flag = 0; break; } } return flag; } int checkArmstrongNumber(int number) { int originalNumber, remainder, result = 0, n = 0, flag; originalNumber = number; while (originalNumber != 0) { originalNumber /= 10; ++n; } originalNumber = number; while (originalNumber != 0) { remainder = originalNumber%10; result += pow(remainder, n); originalNumber /= 10; } // condition for Armstrong number if(result == number) flag = 1; else flag = 0; return flag; } int main() { int n, flag; cout<<"Enter a positive integer: "; cin>>n; // Check prime number flag = checkPrimeNumber(n); if (flag == 1) cout<<n<<" is a prime number."<<endl; else cout<<n<<" is a not prime number."<<endl; // Check Armstrong number flag = checkArmstrongNumber(n); if (flag == 1) cout<<n<<" is an Armstrong number."<<endl; else cout<<n<<" is not an Armstrong number."<<endl; } |
Output: