Commas to terminate

So I have the code completely done but when I execute and out put the numbers my answer comes out:

Enter integer: 2

Factors of all number up to 2
1: 1,
2: 1, 2,
when the actual answer should be:

Enter integer: 2

Factors of all number up to 2
1: 1
2: 1, 2

the difference is my code adds a comma after the last number. how do I fix this?

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
#include <iostream> 
using namespace std; 
int main()
 { 
    int n; //variable
   
    cout << "Enter integer: ";                     //tells user what to input
    cin >> n;                                      //user input
    
   
    while(n<0)                                     //while loop if the value entered is negative
      {
	cout <<"Number must be positive."<<endl;   //repeates user input
	cout <<"Enter integer: ";
	cin >>n;
      }
 cout <<endl;
 cout << "Factors of all number up to "<< n <<endl; //ouputs the factors
    for ( int i= 1; i <= n; ++i )
      { 
        cout << i << ":"; 
       
	for ( int j= 1; j <= i; ++j ) 
           
	  if ( (i % j) == 0)
	   
	    
	    cout <<" "<< j <<",";
            cout <<endl;
	  
    } 
   
    return 0; 
}
Last edited on
Wait, so if there is one number, it should have a comma after it, but if there is more than one number, the last number should not have a comma after it? How does that make any sense?
Sorry I edited it. I just copied and pasted the output twice and forgot to delete the other comma after the one. it should look like:
Factors of all number up to 2
1: 1
2: 1, 2

not
Factors of all number up to 2
1: 1,
2: 1, 2,
Generally, the trick used is to have an if statement at the start of the loop that checks if it is not the first iteration, and if so, add the separator before the output.
Topic archived. No new replies allowed.