Write a program to print all prime numbers up to given number

Write a program to print all prime numbers up to given number


// Write a program to print all prime numbers up to given number
// Eg: 4 -> 2 3, 10 -> 2 3 5 7
// Author:- aimforjob.com
#include
int main(){
    int n,i;
    printf("Enter a positive integer:");
    scanf("%d",&n); // input from user
    while(n<=0){
         printf("Please enter positive integer only:");
         scanf("%d",&n);      
    }
    if(n==1){
         printf("1 is neither prime nor composite number")    
    }
    else{
         for(i=2;i<=n;i++){
              if(prime(i)){ // checking if prime or not
                   printf("%d ",i); // printing if prime  
              }            
         }
    }
    getch();
}
int prime(int n){ // defining 'prime' function
    int i;
    for(i=2;i<=n/2;i++){
         if(n%i==0){
   return 0;      
         }            
    }
    return 1;
}

No comments:

Post a Comment