Find Prime Number ( Method2 ) Example Program In C++
On this page (6sections)
About this program
This is an example program in c common example program. Read the concept first: C++ Variables and Data Types, then study the code and output below.
Definition:
A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
for example,
5 is prime, as only 1 and 5 divide it.
List Prime Numbers Example Program (Method 2)
/* Example Program For Find Prime Number Using For Loop In C++
little drops @ thiyagaraaj.com
Coded By:THIYAGARAAJ MP */
#include<iostream>
#include<conio.h>
#include<math.h> // Math.h For sqrt function
using namespace std;
int main() {
// Variable Declaration
int n;
// Get Input Value
cout << "Enter the Number :";
cin>>n;
cout << "List Of Prime Numbers Below " << n << endl;
//for Loop Block For Find Prime Number
for (int i = 2; i < n; i++) {
bool prime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
prime = false;
break;
}
}
if (prime) cout << i << endl;
}
// Wait For Output Screen
getch();
return 0;
}
Sample Output
Enter the Number :50
List Of Prime Numbers Below 50
5
7
11
13
17
19
23
29
31
37
41
43
47
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
- C++ Variables and Data Types — Tutorial — data types and variable declaration.
- Factorial Using Loop Example Program In C++ — More in c common example program.
- Factorial Using Function Example Program In C++ — More in c common example program.
Frequently Asked Questions
What does this C++ program do?
It is a C++ example program that demonstrates Find Prime Number ( Method2 ), including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses loops to iterate over data, conditional logic and reading user input, illustrating a common pattern in C++ programming.