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:
- Get the input length from the user.
- One number takes modulo division with all other numbers.
- Then count how many times the number divisible by other.
- If the count value less than two will represent the prime number.
- 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(); }