Click here to Skip to main content
15,887,821 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I was making a program takes maximum number (n) from keyboard and finds the divisors and sum of this divisors for each integer from 1 to n,when i didn't use the sum part of my code it prints perfectly, but when i try to print with sum it gives wrong numbers:

it works perfectly :
C++
<pre>int main()
{
	
	int x,n,sum,c;
	printf("Enter a maximum number :");
	scanf("%d",&n);
	

	for(c=1;c<=n;c++)
	{
	
		for (x = 1; x <= c; x++)
		{
			if(c%x == 0)
			{		
			printf("%d ",x);
			
		
			}

		}
		printf("\n");
	}

}


What I have tried:

when i try this to add sum part it gives wrong numbers:
C++
int main()
{
	
	int x,n,sum,c;
	printf("Enter a maximum number n :");
	scanf("%d",&n);
	

	for(c=1;c<=n;c++)
	{
	
		for (x = 1; x <= c; x++)
		{
			if(c%x == 0)
			{		
			printf("%d ",x);
			sum=0;
			sum=sum+x;
			printf("%d",sum);
			
		
			}

		}
		printf("\n");
	}
Posted
Updated 20-Oct-17 7:58am
Comments
ZurdoDev 20-Oct-17 13:53pm    
Debug it. Debugging is the most important thing you'll ever do in coding so learn to do it.

1 solution

Well... the debugger would show you the problem pretty quickly, but you should be able to see it yourself with a quick glance over the code.
for (x = 1; x <= c; x++)
{
    if(c%x == 0)
    {
    printf("%d ",x);
    sum=0;
    sum=sum+x;
    printf("%d",sum);
    }
Hint: what is the value of sum when you try to add the latest value to it?

Moving one line of code will fix it.
 
Share this answer
 
Comments
CPallini 20-Oct-17 17:02pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900