C++

Program Written In C++ That Displays Prime Integers From 1 To N And 1 To 100

Two applications will be shown to us in this tutorial. 1) The first program displays prime numbers between 1 and 100. 2) The second program outputs the prime integers between 1 and n using the value of n (as given by the user).

1) Illustration: Showing prime integers from 1 to 100

Between 1 and 100, this program displays all prime numbers. You need be familiar with user-defined functions, for loops, and if-else control statements in C++ in order to comprehend this 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

2) Illustration: Showing prime numbers from 1 to n

This program searches for all prime numbers between 1 and n using the value of n (supplied by the user).

#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:50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button