Prime Number Program in C

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:
prime
Download the source code

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in C and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s