×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to check whether number is Prime or Not

This program will read an integer number and check whether it is Prime number of not. Primer Numbers are those numbers which divides by itself, for example 19 is a Primer Number because it can be divided by 19 Only.

Checking whether number is Prime or Not in C

To check number is prime or not, we will divide numbers from 2 to Number/2 in a loop. If it is divisible by any number between the 2 to 19/2, number will not be primer but here 19 will not be divided so it is a prime number.

C program to check whether number is Prime or Not

/*Program to check entered number is whether prime or not.*/
 
#include <stdio.h>
 
int main()
{
    int tally;
    int number;
    unsigned char flag=0;
 
    printf("Enter an integer number : ");
    scanf("%d",&number);
 
    for(tally=2; tally<=(number/2); tally++)
    {
        if(number%tally ==0)
        {
            flag=1;
            break;
        }
    }
     
    if(flag==0)
        printf("\n%d is a prime number.",number);
    else
        printf("\n%d is not a prime number.",number);
 
    return 0;
}

Using user-define function

/*Program to check entered number is whether prime or not.*/
 
#include <stdio.h>
 
/*function to check number is Prime or Not*/
int isPrime(int num)
{
    unsigned char flag=0;
    int tally;
     
    for(tally=2; tally<=(num/2); tally++)
    {
        if(num%tally ==0)
        {
            flag=1;
            break;
        }
    }
     
    if(flag==0)
        return 1; /*prime number*/
    else
        return 0; /*not a prime number*/
}
 
int main()
{
    int number;
     
    printf("Enter an integer number : ");
    scanf("%d",&number);
  
 
    if(isPrime(number))
        printf("\n%d is a prime number.",number);
    else
        printf("\n%d is not a prime number.",number);
  
    return 0;
}

Output

First run:
Enter an integer number : 29 
 
29 is a prime number.

Second run:
Enter an integer number : 123
 
123 is not a prime number. 

Third run:
Enter an integer number : 179
 
179 is a prime number.

C Number Manipulation Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.