In today’s tutorial we are going to learn about writing prime number program using C.A number is said to be prime number if and only if it is divisible by 2 otherwise it is not a prime number.
The meaning of divisibility by 2 is the remainder should be 0.To find the remainder of a division we use the operator %.The operator / gives you the quotient of the division.In order to decide whether the number is prime number or not we need to check the remainder of the division of the number with 2.
Let us write the program use the % operator.In the below program we ask the limit from the user,upto which number we need to find the prime numbers.The output is the list of all prime number from 2 to the given limit.
#include<stdio.h> #include<conio.h> void main() { int n,i,j,flag=0; clrscr(); printf("\nEnter the limit to find the prime numbers:"); scanf("%d",&n); for(i=2;i<n;i++) { flag=0; for(j=2;j<i;j++) { if(i % j == 0) flag++; } if(flag == 0) { printf("\nPrime number : %d",i); } } getch(); }
Output:
Download the source code