Oct 6, 2013 at 9:35pm UTC
If the number 4 is entered, the output should be the following:
1: 1
2: 1, 2
3: 1, 3
4: 1, 2, 4,
My output, however, is different but I know its an error with the comma.f
1: 1, , ,
2: 1, 2, ,
3: 1, , 3,
4: 1, 2, , 4
Any help with this little comma problem is greatly appreciated!
Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
using namespace std;
int main()
{
int n(0), j(0);
int i(0);
cout << "Enter integer: " ;
cin >> n;
while (n < 1)
{
cout << "Number must be positive." << endl;
cout << "Enter integer: " ;
cin >> n;
}
cout << endl;
cout << "Factors of all numbers up to " << n << endl;
for (i = 1; i <= n; i++)
{
cout << i << ": " ;
for (j = 1; j <= n; j++)
{
if (i % j == 0)
{
cout << j;
}
if (j != i)
{
cout << ", " ;
}
}
cout << endl;
}
}
Last edited on Oct 6, 2013 at 10:04pm UTC
Oct 6, 2013 at 9:48pm UTC
¿why there are so many empty lines?
Put the comma only if the number is a factor
Oct 7, 2013 at 2:35am UTC
You have to get rid of your second if statement. That just fills non factors with commas. You must add it to factors. So think of a way to add commas right after a successful factor. For example, on your if statement, make it: cout << j << ", ";
but when you only do that, it adds a comma after the last one. So make another if statement that doesnt put it on the last integer.
Oct 7, 2013 at 10:27pm UTC
simply change that "if (i == j)
{ cout << j; }"
block to
" if ( i>j) { cout << ", "}"
I think Chris will give you full points on that then!!