#include <iostream>
usingnamespace 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;
}
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
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.