Program to print prime numbers up to n

Program to print prime numbers up to n

Question:

To print the prime numbers up to the given limit.

Logic:

  • Get the input length from the user.
  • Then divide the number with all other numbers.
  • If the number is divisible by more than two numbers and then it is the prime number.
  • Then print all the prime numbers up to the given length.

Algorithm:

  1. Get the input length from the user.
  2. One number takes modulo division with all other numbers.
  3. Then count how many times the number divisible by other.
  4. If the count value less than two will represent the prime number.
  5. Repeat step 2 to 4 up to the given length.

Program:

#include<stdio.h>
void main()
{
   int i,j,count,n,a;
   clrscr();
   printf("Enter the limit to print prime numbers:");
   scanf("%d",&n);
   printf("1");
   for(i=2;i<=n;i++)
   {
     for(j=2;j<=i;j++)
     {
	a=i%j;                //number takes modulus with all other numbers
	if(a==0)              //only the number divides with j
	{
	   count++;
	}
     }
     if(count<2)              //means that it can't divide's only with one number
     {
	printf("%5d",i);
     }count=0;                //initializes count for next numbers counting 
   }getch();
}

 

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x