# What's wrong with this program?

• 08-08-2012
KiRa11Love
What's wrong with this program?
Code:

```#include <stdio.h> #include <conio.h> main() {     int p,N[100] = {0},d,c,E;     printf("Input a number: ");     scanf("%d",&p);     for(d=1,c=0;d<p;d++)     {         if(p%d==0)         {             N[c]=d;             c++;         }     }     c=0;     while(N[c]!=0)     {         E=E+N[c];     }     printf("\n%d",E); }```
So I have made a program for computing the sum of the factors of the input but the problem is that it doesn't print the sum. I can't see the error in this code so can someone indicate the problem. Thanks.
• 08-08-2012
theju112
Code:

```#include <stdio.h>   main() {     int p,N[100] = {0},d,c,E=0;     printf("Input a number: ");     scanf("%d",&p);     for(d=1,c=0;d<=p;d++)     {         if(p%d==0)         {             N[c]=d;             c++;         }     }     c=0;     while(N[c]!=0)     {         E=E+N[c];         c++; // see here since you are not incrementing c in your code, the while loop becomes an infinite  one.     }     printf("\n%d",E); }```
its something common for beginners. you take care of the important part(to find the sum or the product or whatever but forget to do the smaller steps.) increment the index c in the while loop until there is a zero..hope it helps!!

but im not getting the right answer when i input 20 the answer should be 1+2+5+10+20=38.
a number is a factor of itself:biggrin: you missed that point there..
by the way initialize E to zero...
• 08-08-2012
KiRa11Love
When I tried what you told me. The sum is something unexpected. When I enter "32", it prints a unexpected number. But thanks for the answer, I didn't saw that error. But still more problem.
• 08-08-2012
theju112
Quote:

Originally Posted by KiRa11Love
When I tried what you told me. The sum is something unexpected. When I enter "32", it prints a unexpected number. But thanks for the answer, I didn't saw that error. But still more problem.

initiaize E to zero(see line 6 in the code)...otherwise some garbage value will be stored there..thats your problem i guess..my code works fine for 32..it gives 63...hit like if it works:p

hint: if you input 20, the sum of factors includes 20 also...are you checking if a number is a factor of itself?? just see upto what number you are checking for factors!
• 08-08-2012
KiRa11Love
It worked!... Thanks Man... :) Now I can continue on my life. XD
• 08-08-2012
Elysia
This looks like C, not C++. Mix up?