Write the function perfect that checks if a number is perfect or not. The function returns 1 if the number is perfect and 0 otherwise. Note that an integer N is considered perfect if the sum of the divisors of N, excluding the number N itself, is equal to the number N.

Example: 6 is perfect

Write the function ReadArray that allows to read the value of an array of size M. All the elements of the array should be between 10 and 100.

Write a main program that declares an array A of maximum size 20. The program should prompt the user for the effective size of A (should be positive), and read its values using the function ReadArray.  Then the program should count and print the number of perfect numbers in A.

 


Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>

int perfect(int x) {
	int s = 0, i;
	for (i = 1; i <= x / 2; i++)
		if (x%i == 0)
			s += i;
	if (s == x)
		return 1;
	return 0;
}

void ReadArray(int X[], int M) {
	int i;
	for (i = 0; i < M; i++) { 
		do {
			printf("Enter an element: ");
			scanf("%d", &X[i]); 
		} while (X[i] < 10 || X[i] > 100);
	}
}

void main() {
	int A[20], M, i, c = 0; 

	do {
		printf("Enter the dimension: ");
		scanf("%d", &M);
	} while (M <= 0);

	ReadArray(A, M); 

	for (i = 0; i < M; i++) 
		if (perfect(A[i]) == 1)
			c++;

	printf("The number of perfect  numbers in the array = %d\n", c);
	getch();
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Checking whether all the elements of an array belong to another array