user20161989
user20161989

Reputation:

c++ How do write a number sequence separated with comma's correctly?

The sequence consists of all numbers from 1 to N (inclusive), n(1<=n<=100). All the odd numbers are listed first, then all the even numbers. For example you input 8 and the code prints this: 1,3,5,7,2,4,6,8. Although when I input an odd number it adds a comma in the end. It's my first time here, no idea how to post it correctly...

Even numbers here
> for(int i=1;i<=n;i++){
  if(i%2!=0){
    cout<<i<<",";
  }
}
Odd numbers here
for(int i=1;i<=n;i++){
  if(i%2==0){
    if(i==n){
      cout<<i;
    }
    else{
    cout<<i<<",";
     }
  }
}

Upvotes: 0

Views: 387

Answers (2)

Bob__
Bob__

Reputation: 12789

The sequence consists of all numbers from 1 to N (inclusive).

So you always have to print 1. Then you just have to print a comma before the (eventual) other numbers.

void print_all_numbers_1_n(int n)
{
  std::cout << '1';
  for (int i = 3; i <= n; i += 2)
    std::cout << ", " << i;
  for (int i = 2; i <= n; i += 2)
    std::cout << ", " << i;
  std::cout << '\n';
}

Upvotes: 1

selbie
selbie

Reputation: 104589

My pattern. The comma doesn't get postfixed. It gets prefixed on everything but the first item.

// print odd
for (int i = 1; i <= n; i += 2)
{
   if (i != 1)
   {
      cout << ",";
   }
   cout << i;
}
for (int i = 2; i <= n; i += 2)
{
  cout << ",";
  cout << i;
}

Or simplified:

for (int i = 1; i <= n; i += 2)
{
   cout << ((i == 1) ? "" : ",") << i;
}
for (int i = 2; i <= n; i += 2)
{
  cout << "," << i;
}

Upvotes: 1

Related Questions