C++ Program to Print Prime Numbers from 1 to N using For loop
C++ program to print prime numbers from 1 to N using for loop of any range.
In this article, you will learn how to print prime numbers between 1 to N using for loop.
Example
Enter the range number to print the prime numbers:
100
The prime numbers between 1 and 90 are:
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
Sample of Prime Numbers
You should have knowledge of the following topics in c++ programming to understand these programs:
- C++
main()
function - C++
for
loop - C++
while
loop
Source Code
// C++ Program to Print Prime Numbers from 1 to N using For loop
#include <iostream>
using namespace std;
int main() {
int x, i, j, f;
cout << "Enter the range number to print the prime numbers:\n";
cin >> x;
cout << "\n\nThe prime numbers between 1 and " << x << " are:\n\n";
for (i = 1; i <= x; i++) {
// They are niether prime nor composite if as skip 0 and 1
if (i == 1 || i == 0) {
continue;
}
f = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
f = 0;
break;
}
}
// f = 1 means i is prime and f = 0 means i is not prime
if (f == 1) {
cout << " " << i;
}
}
return 0;
}
Output
Enter the range number to print the prime numbers:
100
The prime numbers between 1 and 90 are:
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
Explanation
In this given program, we have taken input 100
from the user via the system console then we applied the standard formula to print the prime numbers.
After the whole calculation, It will return the 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
the output of the above program.