2

I have a list of numbers that are printed:

1: 1,
2: 1, 2,
3: 1, 3,

How do I not include that last comma on each line?

for ( int i = 1; i <= x; ++i )
  {
    cout << i << ": ";
    for ( int j = 1; j <= i; ++j )
    {
      if ( i % j == 0 )
      {
        cout << j << ", ";
      }
    }
    cout << endl;
  }
calf
  • 861
  • 2
  • 11
  • 23

4 Answers4

2

Try this:

for ( int i = 1; i <= x; ++i )
{
cout << i << ": ";
for ( int j = 1; j <= i; ++j )
{
  if (i==j) {
      cout << j;      
   } else if ( i % j == 0 ) {
       cout << j << ", ";
  }
}
cout << endl;
}
codedude
  • 6,244
  • 14
  • 63
  • 99
1

Try to check if number is the last, smth like:

for (int i = 1; i <= x; i++)
{
    cout << i << ": ";
    for (int j = 1; j <= i; j++)
        if (!(i % j))
        {
            if (j != i)
                cout << j << ", ";
            else
                cout << j << endl;
        }
}
Necronomicron
  • 1,150
  • 4
  • 24
  • 47
0
for ( int i = 1; i <= x; ++i )
{
    cout << i << ": ";
    for ( int j = 1; j <= i; ++j )
    {
        if ( i % j == 0 )
        {
            cout << j;
            if (i != j) {
                cout << ", ";
            }
        } 
    }
    cout << endl;
}
Gopi Krishna
  • 486
  • 2
  • 6
0

Since you always output 1, start checking at 2

for ( int i = 1; i <= x; ++i )
{
   cout << i << ": 1";
   for ( int j = 2; j <= i; ++j )
   {
        if ( i % j == 0 )
        {
             cout << ", " << j;
        }
   }
   cout << endl;
}

Alternatively, you could play with the separator

for ( int i = 1; i <= x; ++i )
{
   char sep = ':'
   cout << i;
   for ( int j = 1; j <= i; ++j )
   {
        if ( i % j == 0 )
        {
             cout << sep << " " << j;
             sep = ',';
        }
   }
   cout << endl;
}
cup
  • 7,589
  • 4
  • 19
  • 42