In the following example, we will check whether the given number (496) is a Perfect number or not.
Example
C# Compiler
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int num =496;
int i =1;
int total =0;
for(i=1; i<num; i++)
{
if(num % i ==0)
total += i;
}
if(total == num)
Console.Write("{0} is a perfect number", num);
else
Console.Write("{0} is not a perfect number", num);
}
}
}
Output
496 is a perfect number
Perfect Numbers between the Given Range
In the following example, we will find all the Perfect numbers between 1 and 1000.
Example
C# Compiler
using System;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
int start =1;
int end =1000;
int i =1;
int total =0;
int flag =0;
Console.Write("Perfect numbers between {0} and {1}:\n", start, end);
for(start=start; start<=end; start++)
{
for(i=1; i<start; i++)
{
if(start % i ==0)
total += i;
}
if((total == start) && (start !=0))
{
flag =1;
Console.Write(start+" ");
}
total =0;
}
if(flag ==0)
Console.Write("There in no perfect number between the given range");
}
}
}
Output
Perfect numbers between 1 and 1000:
6 28 496
Check Whether the Given Number is Perfect or Not
In the following example, we will check whether the given number is a Perfect Number or Not.
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 =1;
int total =0;
for(i=1; i<num; i++)
{
if(num % i ==0)
total += i;
}
if(total == num)
Console.Write("{0} is a perfect number", num);
else
Console.Write("{0} is not a perfect number", num);
}
}
}
Output
Enter a (int) number: 25
25 is not a perfect 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#.