The Program in C# Program to Check If Given Number is perfect number or not is given below:
using System;
namespace PerfectNumber
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Codeauri Family, enter a number to check if it is a perfect number:");
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
sum += i;
}
}
if (sum == n)
{
Console.WriteLine("Yes, " + n + " is a perfect number.");
}
else
{
Console.WriteLine("No, " + n + " is not a perfect number.");
}
Console.ReadLine();
}
}
}
Output:
Hello Codeauri Family, enter a number to check if it is a perfect number:
28
Yes, 28 is a perfect number.
Pro-Tips💡
Here are the step by step execution of above program:
- The code starts by importing the
System
namespace. - The program defines a
Program
class with aMain
method that takes an array of strings as arguments (string[] args
). - In the
Main
method, the program prompts the user to enter a number. The number is then stored in then
variable. - The program uses a
for
loop to iterate from 1 ton - 1
. For each iteration, the program checks if the current iteration number (i
) is a factor ofn
(n % i == 0
). - If the current iteration number is a factor of
n
, the program adds it to thesum
variable. - After the loop, the program checks if
sum
is equal ton
. - If
sum
is equal ton
, the program prints a message indicating thatn
is a perfect number. - If
sum
is not equal ton
, the program prints a message indicating thatn
is not a perfect number. - The program ends with a
ReadLine
method call, which waits for the user to press Enter before closing the program.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.