How to print even numbers in c++?

Member

by rollin , in category: C/C++ , 2 years ago

How to print even numbers in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by yadira.tillman , 2 years ago

@rollin try this code to print even numbers in C++:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>

int main(int argc, char *argv[]) {

    int i = 1;
    while (i <= 100) {
        if (i % 2 == 0) {
            std::cout << i;
        }
        i++;
    }

    return 0;
}


Member

by carey , 10 months ago

@rollin 

There are various ways to print even numbers in C++. Here are a few examples:

  1. Using a for loop:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include 

int main() {
    int n;
    std::cout << "Enter a number: ";
    std::cin >> n;

    std::cout << "Even numbers from 1 to " << n << " are: ";
    for (int i = 1; i <= n; i++) {
        if (i % 2 == 0) {
            std::cout << i << " ";
        }
    }

    return 0;
}


  1. Using a while loop:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include 

int main() {
    int n, i = 1;
    std::cout << "Enter a number: ";
    std::cin >> n;

    std::cout << "Even numbers from 1 to " << n << " are: ";
    while (i <= n) {
        if (i % 2 == 0) {
            std::cout << i << " ";
        }
        i++;
    }

    return 0;
}


  1. Using a do-while loop:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include 

int main() {
    int n, i = 1;
    std::cout << "Enter a number: ";
    std::cin >> n;

    std::cout << "Even numbers from 1 to " << n << " are: ";
    do {
        if (i % 2 == 0) {
            std::cout << i << " ";
        }
        i++;
    } while (i <= n);

    return 0;
}


Regardless of the method used, these programs will prompt the user to enter a number, and then print all even numbers from 1 to that number.