If you have a number to add use this
sum=sum+a;
or sum+=a; Both do the same thing of adding the value a to the value sum.
you will need to expand you if to only add to sum if a is a factor
you can use this construct
if (condition)
{
// statement 1
// statement 2
//...
}
Note the braces allow multiple statements if the condition is true
Lastly, thanks for reading the forum rules before posting and feel free to post your next version, when/if you get stuck.
StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
I think this is what you want. Add a temp and use it to add together your factors.
#include <iostream>
using namespace std;
main()
{
int a;
int b;
int temp = 0;
b = 0;
cout<<"Enter a number:";
cin>>a;
for (b=2; b<=a; b++)
{
if (a % b == 0)
cout << b << " is a factor of " << a << endl;
temp = temp + b;
}
cout << "The sum of the factors is " << temp;
return 0;
}
MatEpp
Junior Poster in Training
79 posts since Jan 2009
Reputation Points: 21
Solved Threads: 12
Sorry code tag didn't work.
MatEpp
Junior Poster in Training
79 posts since Jan 2009
Reputation Points: 21
Solved Threads: 12
Not a problem, lets consider the following code:
int sum=0;
for(int i=0;i<=10;i++)
{
sum+=i;
}
std::cout<<"Sum == "<<sum<<std::endl;
Now what you have there is the sum of the fiirst 10 numbers (55), you add up the even numbers upto 10.
int sum=0;
for(int i=0;i<=10;i++)
{
if (i % 2 )
{ sum+=i; }
}
std::cout<<"Sum (even)== "<<sum<<std::endl;
That is very very close to the code that you are trying to write. It has a loop, and a condition that must be met. note that the initialization of sum is outside of the loop, so is the printing of the result.
StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
Take my code and look at the loop. It is a test code so you can get to understand loops.
Change the 10 to 11 then recompile and run. Then change the 11 to 12 and recompile and run. Now do you see how it works?
StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
Oh I see what's going on. Just study the loop like StuXYZ is saying. And I wrote bad code earlier. Here it is corrected.
if (a % b == 0)
{
cout << b << " is a factor of " << a << endl;
temp = temp + b;
}
cout << "The sum of the factors is " << temp;
And the concept behind this is to create an integer that is zero. Then you have your factors as b.
So say b = 1, then 1 + 0 = 1. temp = 1
Then say b equals 2 = 1 + 2 =3. temp = 3
And so on until the loop stops.
Hope that helps.
MatEpp
Junior Poster in Training
79 posts since Jan 2009
Reputation Points: 21
Solved Threads: 12