C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Monday, May 27, 2019

C++ Program Prime series - All Prime numbers 1 to n


Write a program in C language to print all prime numbers between 1 and a given number n input by user at run time.

This C program will display all prime numbers from 1 to a user supplied  number n.
// cprime, prime in c++, prime series in c++, n prime


// C++ program to input a number n
//then prints prime number series from 1 to n
//that is prints all prime between 1 to n
cprime-numbers-series-from-1-to-N-program-source-code
cprime-numbers-series-from-1-to-N-program-source-code

#include <iostream>
using namespace std;

int checkPrimeNumber(int);

int main() {
   bool isPrime;
   int n, num;
   cout<<"Enter the value of n:";
   cin>>num;
   for(int n = 2; n <= num; n++)
   {
       // if n is prime then boolean variable isPrime will be true
       isPrime = checkPrimeNumber(n);

       if(isPrime == true)
          cout<<n<<" ";
   }
   return 0;
}


// Function that checks whether n is prime or not
int checkPrimeNumber(int n) {
   bool isPrime = true;

   for(int i = 2; i <= n/2; i++) {
      if (n%i == 0)
      {
         isPrime = false;
         break;
      }
   }
   return isPrime;
}

//Output:

//Enter the value of n:50
//2 3 5 7 11 13 17 19 23 29 31 37 41 43 47


Share:

EasyCPPprogramming.blogspotcom

Labels