C program for prime numbers between 1 to n




Program or code for prime numbers between 1 to n in c language

#include<stdio.h>

int main(){

    int num,i,count,n;
    printf("Enter max range: ");
    scanf("%d",&n);

    for(num = 1;num<=n;num++){

         count = 0;

         for(i=2;i<=num/2;i++){
             if(num%i==0){
                 count++;
                 break;
             }
        }
        
         if(count==0 && num!= 1)
             printf("%d ",num);
    }
  
   return 0;
}

Sample output:
Enter max range: 50
2 3 5 7 11 13


Algorithm:


Definition of prime number:

A natural number greater than one which has not any other divisors except 1 and itself is called prime number. In other word we can say which has only two divisors 1 and number itself. For example: 5

Their divisors are 1 and 5.

Note: 2 is only even prime number.

Logic for prime number in c
We will take a loop and divide number from 2 to number/2. If the number is not divisible by any of the numbers then we will print it as prime number.

Example of prime numbers : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 etc.



10 comments:

Anonymous said...

Nice Qusation...But I not minded.......

Anonymous said...

Print all the prime numbers which are below the given number separated by comma

Unknown said...

used very much tq......

Anonymous said...

is this type of algorithm consider as series of prime numbers

Unknown said...

Print all the Armstrong number upto n

Unknown said...

Why is there num/2 ?

Unknown said...

Don't add break; after count++....then it is running properly

Unknown said...

It worked thanks

Tanishq said...

How can I find also their total Sum of Prime numbers between 1 to n?

Mudassar Iqbal said...

#include
int main(){
int n, sum=0;
printf("Enter any number to find it is prime or not \n");
scanf("%d", &n);
printf("Following are the prime numbers between 1 to n \n");
for(int i=1; i<n; i++){
int c=0;
for(int j=2; j<i; j++){
if(i%j==0){
c++;
break;
}

}
if(c==0 && i!=1){
sum=sum+i;
printf("%d \n", i);
}
}
printf("Sum of prime numbers between 1 and n is %d", sum);
}