trying to write a perfect number algorithm but can’t get right output even thought 28 is a perfect number.
#include <stdio.h>
int main() {
int x = 0;
int sum;
printf("enter a number: ");
scanf("%d", &x);
for(int i = 1;i < x;i++) {
if(x % i==0) {
printf("%d ", i);
sum = sum + i;
}
}
printf("\n");
if(sum == x) {
printf("it's a perfect number");
}else {
printf("it's not a perfect number");
}
}
>Solution :
The issue might be coming from the way you declare the sum.
int sum;
When declaring it like this you only allocate space for an int in your memory but never set the value in the memory.
Wo when you do a sum = sum + 1, the sum is not defined and you try to add something to it. It will read in the memory a random value that is remaining here.
To prevent that, when you create an integer set it’s default value
ex : int sum = 0;