C++ program to print all Even and Odd numbers from 1 to N
Given a number N, the task is to print N even numbers and N odd numbers from 1.
Examples:
Input: N = 5
Output:
Even: 2 4 6 8 10
Odd: 1 3 5 7 9
Input: N = 3
Output:
Even: 2 4 6
Odd: 1 3 5
Approach:
- For Even numbers:
- Even numbers are numbers that are divisible by 2.
- To print even numbers from 1 to N, traverse each number from 1.
- Check if these numbers are divisible by 2.
- If true, print that number.
- For Odd numbers:
- Odd numbers are numbers that are not divisible by 2.
- To print Odd numbers from 1 to N, traverse each number from 1.
- Check if these numbers are not divisible by 2.
- If true, print that number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printEvenNumbers( int N)
{
cout << "Even: " ;
for ( int i = 1; i <= 2 * N; i++) {
if (i % 2 == 0)
cout << i << " " ;
}
}
void printOddNumbers( int N)
{
cout << "\nOdd: " ;
for ( int i = 1; i <= 2 * N; i++) {
if (i % 2 != 0)
cout << i << " " ;
}
}
int main()
{
int N = 5;
printEvenNumbers(N);
printOddNumbers(N);
return 0;
}
|
Output
Even: 2 4 6 8 10
Odd: 1 3 5 7 9
Time Complexity: O(N)
Auxiliary Space: O(1), As constant extra space is used.
Method: Using bitwise & Operator
C++
#include <bits/stdc++.h>
using namespace std;
void printEvenNumbers( int N)
{
cout << "Even: " ;
for ( int i = 1; i <= 2 * N; i++) {
if (!(i & 1))
cout << i << " " ;
}
}
void printOddNumbers( int N)
{
cout << "\nOdd: " ;
for ( int i = 1; i <= 2 * N; i++) {
if (i & 1 != 0)
cout << i << " " ;
}
}
int main()
{
int N = 5;
printEvenNumbers(N);
printOddNumbers(N);
return 0;
}
|
Output
Even: 2 4 6 8 10
Odd: 1 3 5 7 9
Time Complexity: O(n)
Auxiliary Space: O(1), As constant extra space is needed.
Method: Using bitwise | Operator
C++
#include <bits/stdc++.h>
using namespace std;
void printEvenNumbers( int N)
{
cout << "Even: " ;
for ( int i = 1; i <= 2 * N; i++) {
if ((i | 1)==i+1)
cout << i << " " ;
}
}
void printOddNumbers( int N)
{
cout << "\nOdd: " ;
for ( int i = 1; i <= 2 * N; i++) {
if ((i | 1) == i)
cout << i << " " ;
}
}
int main()
{
int N = 5;
printEvenNumbers(N);
printOddNumbers(N);
return 0;
}
|
Output
Even: 2 4 6 8 10
Odd: 1 3 5 7 9
Time Complexity: O(n)
Auxiliary Space: O(1), As constant extra space is needed.
Method: Using Recursion
C++
#include <bits/stdc++.h>
using namespace std;
void printEvenOdd( int n)
{
if (n <= 0)
{ return ; }
printEvenOdd(n - 2);
cout << n << " " ;
}
int main()
{
int n = 5 ;
cout << "Even: " ;
printEvenOdd(2*n);
cout <<endl<< "Odd: " ;
printEvenOdd(2*n-1);
return 0;
}
|
Output
Even: 2 4 6 8 10
Odd: 1 3 5 7 9
Time Complexity: O(n)
Auxiliary Space: O(n), because of recursive call
Last Updated :
13 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...