w3resource

C Exercises: Check whether a given number is a perfect number or not

C For Loop: Exercise-27 with Solution

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

Visual Presentation:

Check whether a given number is a perfect number or not

Sample Solution:

C Code:

/* 
   Perfect number is a positive number which sum of all positive divisors excluding that number is equal to that number.
   For example, 6 is a perfect number since the divisors of 6 are 1, 2, and 3. Sum of its divisors is 1 + 2 + 3 = 6
*/

#include <stdio.h> // Include the standard input/output header file.

int main()
{
  int n, i, sum; // Declare variables for user input, loop control, and sum.

  printf("Input the number: "); // Prompt the user for input.
  scanf("%d", &n); // Read the value of 'n' from the user.
  sum = 0; // Initialize the sum variable.

  printf("The positive divisors: "); // Print a message to indicate positive divisors are being displayed.

  for (i = 1; i < n; i++) // Loop to find and display positive divisors.
  {
    if (n % i == 0) // If 'i' is a divisor of 'n'.
    {
      sum = sum + i; // Add 'i' to the sum.
      printf("%d  ", i); // Print 'i' as a positive divisor.
    }
  }

  printf("\nThe sum of the divisors is: %d", sum); // Print the sum of the divisors.

  if (sum == n) // Check if the sum of divisors is equal to the original number.
    printf("\nSo, the number is perfect.\n"); // If true, print that the number is perfect.
  else
    printf("\nSo, the number is not perfect.\n"); // If false, print that the number is not perfect.

  return 0; // Return 0 to indicate successful execution.
}


Sample Output:

Input the  number : 56                                                                                        
The positive divisor  : 1  2  4  7  8  14  28                                                                 
The sum of the divisor is : 64                                                                                
So, the number is not perfect.  

Flowchart:

Flowchart : Check whether a given number is perfect number or not

C Programming Code Editor:

Previous: Write a program in C to find the sum of the series 1 +11 + 111 + 1111 + .. n terms.
Next: Write a c program to find the perfect numbers within a given number of range.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.