A Program to Check a Prime Number

In this example, we are giving a program to check whether a number is prime or not. A number can be said prime if the number is divisible only by 1 and itself. For example: 2, 3, 5, 7, 11, 13, 17, 19 etc.


Program to check prime:

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4. int n, i, flag = 0;
  5. cout << "Enter a positive integer: ";
  6. cin >> n;
  7. for (i = 2; i < n / 2; ++i) {
  8. // condition for non prime number
  9. if (n % i == 0) {
  10. flag = 1;
  11. break;
  12. }
  13. }
  14. if (n == 1) {
  15. cout << "1 is neither prime nor composite.";
  16. }
  17. else {
  18. if (flag == 0)
  19. cout << n << "is a prime number.";
  20. else
  21. cout << n << "is not a prime number.";
  22. }
  23. return 0;
  24. }

Output:

Enter a positive integer: 7
7 is a prime number.