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<<",";
}
}
}
CodePudding user response:
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;
}
CodePudding user response:
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';
}
CodePudding user response:
for(int i = 1; i <= n; i =2){
cout << i << ',';
}
int i;
for(i = 2; i <=n-2; i =2){
cout <<i <<',';
}
cout << i 2 << "\n";