C Program to Check Prime and Armstrong Number

C Programming Language Function in C Language (Article) Function in C Language (Program)

4096



Program:

/* 
 Author: Atnyla Developer
*/

#include "stdio.h"
#include "math.h"

int checkPrimeNumber(int n);
int checkArmstrongNumber(int n);

int main()
{
    int n, flag;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    // Check prime number
    flag = checkPrimeNumber(n);
    if (flag == 1)
        printf("%d is a prime number.\n", n);
    else
        printf("%d is not a prime number.\n", n);

    // Check Armstrong number
    flag = checkArmstrongNumber(n);
    if (flag == 1)
        printf("%d is an Armstrong number.", n);
    else
        printf("%d is not an Armstrong number.",n);
    return 0;
}

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;
}

Output:

Output 1:
Enter a positive integer: 407
407 is not a prime number.
407 is an Armstrong number.

Output 2:
Enter a positive integer: 25
25 is not a prime number.
25 is not an Armstrong number. 

Explanation:

To understand this example, you should have the knowledge of following C programming topics:

  • C Programming for Loop
  • C Programming while and do...while Loop
  • C Programming break and continue Statement
  • C Programming Functions
  • Types of User-defined Functions in C Programming
In this program, 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.

This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.