ADVERTISEMENT
ADVERTISEMENT

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.

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.

Check Prime Number using C program

/*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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.