Dremendo Tag Line

Input number and check prime or not using for loop in C++

for Loop - Question 10

In this question, we will see how to input a number and check if it is a prime number or not in C++ programming using for loop. To know more about for loop click on the for loop lesson.

Q10) Write a program in C++ to input a number and check if it is a prime number or not using for loop.

Program

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int i,n,fc=0;

    cout<<"Enter a number ";
    cin>>n;
    for(i=1; i<=n; i=i+1)
    {
        if(n%i==0)
        {
            fc=fc+1;		// counting the factors of the given number
        }
    }

    if(fc==2)		// a prime number has only two factors
    {
        cout<<"Prime Number";
    }
    else
    {
        cout<<"Not Prime Number";
    }
    return 0;
}

Output

Enter a number 17
Prime Number
video-poster