In this tutorial, I am going to write a program that will check whether a number is a Perfect Number or Not.

After completing this tutorial you will be able to understand:

  • Write a Program to check a number is a Perfect Number or not?

What Is Perfect Number?

In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum).

Here you can see an example in below image.

Perfect Number

 

Let’s start writing a Program in C#

Step 1 – Open Visual Studio and create a Console Application using C# with the name PerfectNumberDemo.

Step 2- Navigate to Program.cs file and write the following code into it.
using System;
namespace PerfectNumberDemo
{
class Program
{
static void Main(string[] args)
{
int iNumber, iSum = 0, iTemp;
Console.Write("Enter the Number");
iNumber = int.Parse(Console.ReadLine());
iTemp = iNumber;
for (int iCount = 1; iCount < iNumber; iCount++)
{
if (iNumber % iCount == 0)
{
iSum = iSum + iCount;
}
}
if (iSum == iTemp)
{
Console.WriteLine("\n The Given number is a Perfect Number");
Console.ReadLine();
}
else
{
Console.WriteLine("\n The Given Number is not a Perfect Number");
Console.ReadLine();
}
}
}
}

All done now we need to run the application to see the output of the above program.

Perfect Number

You must also follow the following links:

Abstract Class in C#

Interface in C#

Hope you loved this small session about a simple Program in C#.

Thank You.

Leave a Comment