In this tutorial, we will see two programs 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.
1) Example: Displaying prime numbers between 1 and 100
This program displays the prime number between 1 and 100. To understand this program you should have the knowledge of user-defined functions, for loop, C++ if-else control statement.
#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) Example: 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.
#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
Leave a Reply