Write a C++ Program to Check Whether a Number is Prime or Not

C++ Program to Check Whether a Number is Prime or Not

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn C++ programming concepts. You can learn C++ language at your own speed and time. One can learn concepts of C++ language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

C++ Program to Check Whether a Number is Prime or Not
C++ Program to Check Whether a Number is Prime or Not

Write a C++ Program to Check Whether a Number is Prime or Not

PROGRAM: C++ Program to Check Whether a Number is Prime or Not

/* C++ Program to Check Whether a Number is Prime or Not*/

#include <iostream>
using namespace std;

int main() {

int i, n;
bool is_prime = true;

cout << “Enter a positive integer: “;
cin >> n;

// 0 and 1 are not prime numbers
if (n == 0 || n == 1) {
is_prime = false;
}

// loop to check if n is prime
for (i = 2; i <= n/2; ++i) {
if (n % i == 0) {
is_prime = false;
break;
}
}

if (is_prime)
cout << n << ” is a prime number”;
else
cout << n << ” is not a prime number”;

return 0;
}

Leave a Reply

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