OCJP

Prime Number using for loop

To find the prime number we have to iterate the loop from 2 to half of the number. We have to set a flag variable to 0 and if number is divisible then set flag to 1 and break the loop.

#include<stdio.h>
#include<conio.h>

void main()
{
	int n,i,j,f;
	clrscr();

	printf("\nEnter N :");
	scanf("%d",&n);
	for(i=2;i<=n;i++)
	{
		f=0;
		for(j=2;j<i/2;j++) //To decide i is prime or not
		{
			if(i%j==0)
			{
			f=1;
			break;
			}
		}
	if(f==0)
	printf("\n%d is Prime",i);
	}

	getch();
}

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?