Program to find given number is Prime Number or not in C Language:
This is a basic program to find given number is prime or not.
This is a basic program to find given number is prime or not.
#include <stdio.h>
#include <conio.h>
int main(void){
int a = 0;//this variable is used to store given number
int count = 0;//this variable is used to know how many times given number is divisible.
println("Enter a number: ");
scanf("%d",&a);//taking entered number to a variable
for(int i = 0;i <= a;i++){
if(a%i == 0){
count++;
}
}
if(count == 2){
printf("Given number %d is Prime Number",a);
}
}
Output :
Enter a number : 19
Given number 19 is Prime Number
Output :
Enter a number : 19
Given number 19 is Prime Number
Step 1:
First we find the square root of given number.
Ex: Given number is 19 . Square Root of 19 is 4.358898.
Step 2:
If given number is divisible by less than or equal to 4. Means number is divisible by 1 or 2 or 3 or 4.
Step 3:
Number is not divisible by 1 or 2 or 3 or 4 numbers.So 19 is Prime Number.
Now we can write the above steps convert to C Language.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int main(void){
int inputNumber = 0;
int count = 0;
printf("Enter a number");
scanf("%d", &inputNumber);
int sqrtValue = sqrt(inputNumber);
for(int i = 2;i <= sqrtValue;i++){
if(inputNumber%i == 0){
count++;
}
}
if(count == 1){
printf("Given number %d is Prime Number",inputNumber);
}else{
printf("Given number %d is not a Prime Number",inputNumber);
}
return 0;
}
In above program, for loop is started from 2 value not 1 because Every number is divisible by 1.That's why for loop is start from 2.
See this related posts:
write program to sort integer number
How many ways are there to register jdbc driver
Floyd's triangle
No comments:
Post a Comment