Here we will write a code in C language to check whether the entered number is a prime number or not. Here is a sample code of the Prime Number Program in C.
What is a Prime number?
A natural number will be called a prime number if it is only divisible by 1 and itself. For example, 3 is a prime number because it is only divisible by 1 and itself.
Steps
- First, we ask the user to enter a number
- Then we create a loop from 2 to half of that number.
- Inside the loop using the if statement we will check whether the entered number is divisible by any of number between 2 to half of the entered number.
- If the number is divisible by any of number between 2 to half of the entered number, we will break the loop and print the statement that the entered number is not a prime number.
Statements used
- for loop
- break statement
- % (modules)
- if…..else
Prime Number Program in C
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i;
clrscr();
printf("Enter a number:");
scanf("%d",&num);
if(num==1 ||num==2)
printf("It is a Prime Number");
else{
for(i =2;i<=num/2;i++)
{
if(num%i==0) //check whether num is divisible by i or not
{ printf("It is not a Prime Number");
break;
}
else
if(i==num/2)
printf("It is a prime number ");
}
}
getch();
}
Output:
Enter a number:49
It is not a Prime Number
People are also reading:
- WAP in C++ & Python to Calculate Compound Interest
- WAP in C to calculate the factorial of a number
- How many Centimeters in a Foot through Python?
- WAP to Print the Following Pattern
- Programming in C and Java to convert from octal to decimal
- WAP to Print the Following Triangle
- WAP to create a loading bar
- Most Asked Pattern Programs in C
- WAP to print the truth table for XY+Z
- WAP in C++ and python to find the root of quadratic equation
Leave a Comment on this Post