Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   printing of perfect numbers (http://www.go4expert.com/forums/printing-perfect-t25585/)

cindrilla 21Apr2011 18:09

printing of perfect numbers
 
hi friends i tried this logic to print the perfect numbers but there is no output at all pls can any one tell me wht's the mistake is?the code is as follows
main()
{
int i,j,sum=0;
for(i=1;i<=1000;i++)
{
for(j=1;j<i;j++)
{
if(i%j==0)
sum=sum+j;
}
if(sum==i)
printf("%d",i);
}
getch();
}

teacher 22Apr2011 13:30

Re: printing of perfect numbers
 
your logic is correct but you forget to reinitialize sum=0
here is the correct code..
Code:

main()
{
int i,j,sum=0;
for(i=1;i<=1000;i++)
{
for(j=1;j<i;j++)
{
if(i%j==0)
sum=sum+j;
}
if(sum==i)
printf("%d",i);
sum=0; // insert this line in your code...
}
getch();
}



All times are GMT +5.5. The time now is 10:04.