The following table provides few examples of composite numbers.
Number
Divisor
Result
13
1, 13
Not a Composite Number
15
1, 3, 5, 15
Composite Number
47
1, 47
Not a Composite Number
Using for loop
In the following example, we will check whether the number 12 is a Composite number or not using for loop.
Example
C++ Compiler
#include<iostream>using namespace std;
int main()
{
int num =12;
int i;
int count =0;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count >2)
cout << num <<" is a composite number";
else
cout << num <<" is not a composite number";
return0;
}
In the following example, we will check whether the number 12 is a Composite number or not using while loop.
Example
C++ Compiler
#include<iostream>using namespace std;
int main()
{
int num =12;
int i =1;
int count =0;
while(num >= i)
{
if(num % i ==0)
count++;
i++;
}
if(count >2)
cout << num <<" is a composite number";
else
cout << num <<" is not a composite number";
return0;
}
In the following example, we will check whether the number 12 is a Composite number or not using do while loop.
Example
C++ Compiler
#include<iostream>using namespace std;
int main()
{
int num =12;
int i =1;
int count =0;
do{
if(num % i ==0)
count++;
i++;
}while(i<=num);
if(count >2)
cout << num <<" is a composite number";
else
cout << num <<" is not a composite number";
return0;
}
Check Whether the Given Number is Prime or Composite
In the following example, we will check whether the given number is a Prime number or Composite number.
Example
C++ Compiler
#include<iostream>using namespace std;
int main()
{
int num;
int i =1;
int count =0;
cout <<"Enter a (int) number: ";
cin >> num;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count ==2)
cout << num <<" is a prime number";
else
cout << num <<" is a composite number";
return0;
}