简体   繁体   中英

How can I divide the output numbers in odd and even numbers?

The output is like this (odd numbers: 1even numbers: 2odd numbers: 3even numbers: 4odd numbers: 5even numbers: 6odd numbers: 7even numbers: 8odd numbers: 9even numbers: 10)

Output should be (odd numbers: 1 3 5 7 9, even numbers: 2 4 6 8 10)

int main() {
  int num1,ctr=1,modu,even,odd;
  cout<<"enter a number";
  cin>>num1;

  do {
    if (ctr%2 == 0) {
      cout<<"even numbers: "<<ctr;
      ctr++;
    } else {
      cout<<"odd numbers: "<<ctr;
      ctr++;
    }
  }
  while(ctr<=num1);
  return 0;
}

你输出所有的奇数,然后将ctr设置为2,输出所有的偶数。

In doing this, you need to be careful to print the list of even numbers and odd numbers in separate loops.

I have assumed that you will have no more than 10 inputs. If you will have more, then you need to increase the constant 'limit'.

#include <iostream>

using namespace std;

int main() {
    const int limit = 10;
    int array[limit];
    int num1;
    int ctr = 0;

    while(ctr < limit ) {
        cout << endl << "Please enter a number" << endl;
        cin >> num1;
        array[ctr] = num1;
        ++ctr;
    }

    // print odd numbers
    cout << "Odd numbers: ";
    for(int i = 0; i < limit; i++) {
        if(array[i] %2 == 1) {
            cout << " " << array[i];
        }
    }
    // print even numbers
    cout << "  Even numbers: ";
    for(int i = 0; i < limit; i++) {
        if(array[i] %2 == 0) {
            cout << " " << array[i];
        }
    }
    cout << endl;

    return 0;
}
Output:

Odd numbers:  1 3 5 7 9  Even numbers:  2 4 6 8 10

Process finished with exit code 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM