27.9k views
4 votes
Write a c++ program to print even numbers from 1 to 20​

User Nicodp
by
6.9k points

1 Answer

4 votes

Answer:

#include <bits/stdc++.h>

using namespace std;

// Function to print even numbers

void printEvenNumbers(int N)

{

cout << "Even: ";

for (int i = 1; i <= 2 * N; i++) {

// Numbers that are divisible by 2

if (i % 2 == 0)

cout << i << " ";

}

}

// Function to print odd numbers

void printOddNumbers(int N)

{

cout << "\\Odd: ";

for (int i = 1; i <= 2 * N; i++) {

// Numbers that are not divisible by 2

if (i % 2 != 0)

cout << i << " ";

}

}

// Driver code

int main()

{

int N = 20;

printEvenNumbers(N);

printOddNumbers(N);

return 0;

}

Step-by-step explanation:

Note: This will find both odd and even numbers, you have to change the number above to the number of your choice

For even numbers

Even number 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 number 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

User Jruizaranguren
by
7.1k points