位运算使奇数+1 偶数-1
Problem: Take input from the user (N) and print all EVEN and ODD numbers between 1 to N.
问题:从用户那里输入(N),并打印1至N之间的所有偶数和奇数编号。
Solution:
解:
- Input an integer number (N). - 输入一个整数( N )。 
- Run two separate loops from 1 to N. - 从1到N运行两个单独的循环。 
- In the first loop, check the condition to check EVEN numbers and print them. - 在第一个循环中,检查条件以检查偶数并打印它们。 
- In the second loop, check the condition to check ODD numbers and print them. - 在第二个循环中,检查条件以检查奇数编号并打印它们。 
- To check EVEN/ODD number – find the remainder dividing by 2, if it is 0 then the number will be an EVEN number, else the number will be an ODD number. - 要检查EVEN / ODD号码-找到除以2的余数,如果为0,则该号码将为EVEN号码,否则该号码将为ODD号码。 
C++ program:
C ++程序:
// C++ program to print all
// Even and Odd numbers from 1 to N
#include <iostream>
using namespace std;
// function : evenNumbers
// description: to print EVEN numbers only.
void evenNumbers(int n)
{
int i;
for (i = 1; i <= n; i++) {
//condition to check EVEN numbers
if (i % 2 == 0)
cout << i << " ";
}
cout << "\n";
}
// function : oddNumbers
// description: to print ODD numbers only.
void oddNumbers(int n)
{
int i;
for (i = 1; i <= n; i++) {
//condition to check ODD numbers
if (i % 2 != 0)
cout << i << " ";
}
cout << "\n";
}
// main code
int main()
{
int N;
// input the value of N
cout << "Enter the value of N (limit): ";
cin >> N;
cout << "EVEN numbers are...\n";
evenNumbers(N);
cout << "ODD numbers are...\n";
oddNumbers(N);
return 0;
}
Output
输出量
RUN 1:
Enter the value of N (limit): 11
EVEN numbers are...
2 4 6 8 10
ODD numbers are...
1 3 5 7 9 11
RUN 2:
Enter the value of N (limit): 50
EVEN numbers are...
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
ODD numbers are...
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
翻译自: https://www.includehelp.com/cpp-programs/print-all-even-and-odd-numbers-from-1-to-n.aspx
位运算使奇数+1 偶数-1