In this example, we will create a C# program to determine whether a given number is a perfect number, demonstrating the language’s ability to handle mathematical operations and conditional checks.
Problem Statement
Write a C# program to check whether a given positive integer is a perfect number. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, 28 is a perfect number because the sum of its divisors (1, 2, 4, 7, 14) is equal to 28.
C# Program to Check Whether a Given Number is Perfect Number
using System; class Program { static void Main() { Console.Write("Enter a positive integer: "); int number = Convert.ToInt32(Console.ReadLine()); if (IsPerfectNumber(number)) { Console.WriteLine(number + " is a perfect number."); } else { Console.WriteLine(number + " is not a perfect number."); } } static bool IsPerfectNumber(int num) { if (num <= 0) { return false; } int sumOfDivisors = 0; for (int divisor = 1; divisor < num; divisor++) { if (num % divisor == 0) { sumOfDivisors += divisor; } } return sumOfDivisors == num; } }