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
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int num =12;
int i;
int count =0;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count >2)
Console.Write("{0} is a composite number", num);
else
Console.Write("{0} is not a composite number", num);
}
}
}
Output
12 is a composite number
Using while loop
In the following example, we will check whether the number 12 is a Composite number or not using while loop.
Example
C# Compiler
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int num =12;
int i =1;
int count =0;
while(num >= i)
{
if(num % i ==0)
count++;
i++;
}
if(count >2)
Console.Write("{0} is a composite number", num);
else
Console.Write("{0} is not a composite number", num);
}
}
}
Output
12 is a composite number
Using do while loop
In the following example, we will check whether the number 12 is a Composite number or not using do while loop.
Example
C# Compiler
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int num =12;
int i =1;
int count =0;
do{
if(num % i ==0)
count++;
i++;
}while(i<= num);
if(count >2)
Console.Write("{0} is a composite number", num);
else
Console.Write("{0} is not a composite number", num);
}
}
}
Output
12 is a composite number
Composite Numbers between the Given Range
In the following example, we will find all the Composite numbers between 1 and 10.
Example
C# Compiler
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int start =1;
int end =10;
int count =0;
int i =1;
Console.WriteLine("Composite Numbers between {0} and {1}: ", start, end);
for(start=start; start<=end; start++)
{
for(i=1; i<=start; i++)
{
if(start % i ==0)
count++;
}
if(count >2)
Console.Write("{0} ", start);
count =0;
}
}
}
}
Output
Composite Numbers between 1 and 10:
4 6 8 9 10
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
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a (int) number: ");
int num = Convert.ToInt32(Console.ReadLine());
int i;
int count =0;
for(i=1; i<=num; i++)
{
if(num % i ==0)
count++;
}
if(count ==2)
Console.Write("{0} is a prime number", num);
else
Console.Write("{0} is a composite number", num);
}
}
}
Output
Enter a (int) number: 16
16 is a composite number
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on C# with examples for quick and easy learning.
We are working to cover every Single Concept in C#.