even number

is this how you would write the chunk of code to see if it's an even number?

number = 12;

if (number % 2 == 0)

cout << number << “ is even.” << endl;

else

cout << number << “ is odd.” << endl;
Looks good to me.
Why not try it and see for your self ?
Yes it's good. It'll work. But I would do this to organize.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
bool isEven(const int &number)
{
    return number % 2 == 0;
}
int main()
{
    int number{12}; // you can use copy initializer too '='
    if (isEven(number))
    {
        std::cout << number << " is even" << std::endl;
    }
    else
    {
        std::cout << number << " is odd" << std::endl;
    }
    return 0;
}
Last edited on
Yes thats the simplest way to check whether a number is even or odd. We divide the number by 2 and checks the remainder. If remainder is zero then its an even number. If remainder is not zero then its an off number. I like you ti visit the link given below for line by line execution and explanantion of even or odd program.
http://www.cppbeginner.com/numbers/cpp-program-to-check-whether-a-number-is-even-or-odd
In C++, we use modulus operator to find remainder.
Last edited on
Topic archived. No new replies allowed.