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; } 
5
  • 2
    Please share with us your code... Commented Oct 17, 2013 at 3:42
  • how are you producing these numbers? Commented Oct 17, 2013 at 3:43
  • 1
    Cut it off with some scissors? Please post some code. Commented Oct 17, 2013 at 3:43
  • 2
    I recommend using the backspace key. Commented Oct 17, 2013 at 3:45
  • Instead, print the comma before every item but the first. Commented Oct 17, 2013 at 3:52

4 Answers 4

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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; } } 

2 Comments

Code added. Can't use arrays.
I've made a mistake, already correct it.
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; } 

Comments

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.