0

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<<",";
     }
  }
}
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • instead of doing <= n, could just do – CBredlow Oct 04 '22 at 21:20
  • 4
    You need to post code as text within the question. – Mark Ransom Oct 04 '22 at 21:20
  • https://stackoverflow.com/questions/2310939/remove-last-character-from-c-string – CBredlow Oct 04 '22 at 21:21
  • 1
    Never post pictures of code, and *absolutely* never post links to pictures of code. Questions should be self-contained, and not require us to leave SO to assess. All related code should be included [in your question](https://stackoverflow.com/posts/73953724/edit) as a properly formatted [mcve]. – WhozCraig Oct 04 '22 at 21:21
  • 1
    Print the separator before every item except the first one. – Retired Ninja Oct 04 '22 at 21:25
  • 1
    Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/)). By SE policy, any vandalism will be reverted. – tripleee Oct 06 '22 at 06:41

2 Answers2

1

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

selbie
  • 100,020
  • 15
  • 103
  • 173
1

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';
}
Bob__
  • 12,361
  • 3
  • 28
  • 42