Comma output help

closed account (i8T4izwU)
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
¿why there are so many empty lines?

Put the comma only if the number is a factor
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.
closed account (i8T4izwU)
okay so i changed it slightly. Heres the change:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 for (i = 1; i <= n; i++)
    {

      cout << i << ": ";

      for (j = 1; j <= n; j++)
	{
	  if (i % j == 0)
	  {
	    cout << j << ", ";

	    if (i == j)
	    {
	      cout << j;
	      } 
	  }
	     
	}
      cout << endl;
    } 

I want it to just simply display j without the comma as the last digit. But now it displays

Factors of all numbers up to 7
1: 1, 1
2: 1, 2, 2
3: 1, 3, 3
4: 1, 2, 4, 4
5: 1, 5, 5
6: 1, 2, 3, 6, 6
7: 1, 7, 7


the last digit is right, I just don't want to include the "j,". Would a for loop be better for this? Thanks!
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!!
Topic archived. No new replies allowed.