w3resource

C++ Exercises: Check whether a given number is Perfect or not

C++ Numbers: Exercise-4 with Solution

Write a program in C++ to check whether a given number is Perfect or not.

Visual Presentation:

C++ Exercises: Check whether a given number is Perfect or not

Sample Solution:

C++ Code :

# include <iostream> // Include necessary libraries
# include <string>

using namespace std;

int main()
{
    int i = 1, u = 1, sum = 0, n; // Initialize variables i, u, sum, and n
    cout << "\n\n Check whether a given number is a Perfect number:\n"; // Display message for user
    cout << "------------------------------------------------------\n";

    cout << "Input a number: "; // Ask user for input
    cin >> n; // Get user input and store it in variable n

    while (u <= n) // Loop through numbers from 1 to n
    {
        if (u < n) // Check if u is less than n
        {
            if (n % u == 0) // Check if u is a divisor of n
                sum = sum + u; // Add u to the sum if it's a divisor of n
        }
        u++; // Increment u by 1 in each iteration
    }

    if (sum == n) // Check if the sum of divisors is equal to the number itself
    {
        cout << n << " is a Perfect number." << "\n"; // If the sum is equal to the number, it's a Perfect number
    }
    else
    {
        cout << n << " is not a Perfect number." << "\n"; // If the sum is not equal to the number, it's not a Perfect number
    }
}

Sample Output:

 Check whether a given number is a Perfect number:                                                   
------------------------------------------------------                                               
Input a number: 28                                                                                   
28 is a Perfect number.

Flowchart:

Flowchart: Check whether a given number is Perfect or not

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C++ to find the Abundant numbers (integers) between 1 to 1000.
Next: Write a program in C++ to find Perfect numbers and number of Perfect numbers between 1 to 1000.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/cpp-exercises/numbers/cpp-numbers-exercise-4.php