Q:

C# program to check the given number is a perfect number or not

belongs to collection: C# Basic Programs | basics

0

C# program to check the given number is a perfect number or not

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to check the given number is a perfect number or not, is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to check the given number is a 
//perfect number or not.

using System;

class CheckPerfect
{
    static bool IsPerfect(int number)
    {
        int sum     = 0;
        int iLoop   = 0;

        for (iLoop = 1; iLoop < number; iLoop++)
        {
            if (number % iLoop == 0)
                sum = sum + iLoop;
        }

        if (sum == number)
        {
            return true;
        }
        return false;
    }
    static void Main(string[] args)
    {
        int     number  = 0     ;
        bool    ret     = false ;

        Console.Write("Enter the integer number: ");
        number = int.Parse(Console.ReadLine());

        ret = IsPerfect(number);

        if (ret)
            Console.WriteLine("Given number is perfect number");
        else
            Console.WriteLine("Given number is not perfect number");
    }
}

Output:

Enter the integer number: 6
Given number is perfect number
Press any key to continue . . .

Explanation:

Here, we created a class CheckPerfect that contains two static methods IsPerfect() and Main().

The IsPerfect() method is used to check the given number is perfect or not. Here we find the sum of all divisors of a given number and check the sum of divisors with the number, if both are equal then we return value "true" to the calling method otherwise false will be returned to the calling method.

In the Main() method, we read a positive integer value and then pass the entered number to the IsPerfect() method and then print the appropriate message according to the return value of the IsPerfact() method.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to print the all factors of a given num... >>
<< C# program to print digits of a number into words...