Find prime or composite number using While Loop in C++


This is a C++ program to determine whether a given number is prime or composite. The program first prompts the user to enter a number and stores it in the variable "i". It then initializes "n" to 2 and "prime" to 0.

The program then enters a while loop that checks if "n" is less than "i". If "i" is divisible by "n" (i.e., if "i%n" is 0), the program increments the "prime" variable. The loop then increments "n" by 1. Once the loop has finished, the program checks whether "prime" is equal to 0. If it is, the program prints "This number is Prime"; otherwise, it prints "This number is Composite".

Overall, this program checks every number from 2 to (i-1) to see if i is divisible by any of them. If i is not divisible by any number in that range, then it is prime. However, note that the program could be optimized by only checking up to the square root of i instead of i-1. Also, if i is less than 2, the program would incorrectly identify it as prime.

Source Code

#include<iostream>
using namespace std;
int main()
{
    int i,n=2,a,prime=0;
    cout<<"\nEnter the number:";
    cin>>i;
    while(n<i)
    {
        if(i%n==0)
        {
            prime++;
        }
        n++;
    }
    if(prime==0)
    {
        cout<<"\nThis number is Prime";
    }
    else
    {
        cout<<"\nThis number is Composite";
    }
    return 0;
}
To download raw file Click Here

Output

Enter the number:10
This number is Composite

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples