Google News
logo
C++ Program to display Prime Numbers from 1 to 100 and 1 to n
1) First program prints prime numbers from 1 to 100

2) Second program takes the value of n(entered by user) and prints the prime numbers between 1 and n.

Displaying prime numbers between 1 and 100 :

Program :
#include <iostream>
using namespace std;

int isPrimeNumber(int);

int main()
{
   bool isPrime;
   for(int n = 2; n < 100; n++) {
      // isPrime will be true for prime numbers
      isPrime = isPrimeNumber(n);

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

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

   for(int i = 2; i <= n/2; i++) {
      if (n%i == 0) {
         isPrime = false;
         break;
      }
   }  
   return isPrime;
}
Output :
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

Displaying prime numbers between 1 and n :

This program takes the value of n (input by user) and finds the prime numbers between 1 and n.
Program :
#include <iostream>
using namespace std;

int isPrimeNumber(int);

int main() {
   bool isPrime;
   int count;
   cout<<"Enter the value of n:";
   cin>>count;
   for(int n = 2; n < count; n++)
   {
       // isPrime will be true for prime numbers
       isPrime = isPrimeNumber(n);

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

// Function that checks whether n is prime or not
int isPrimeNumber(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:75
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73