C++ for Beginners: C++ Program to Check Whether Number is Even or Odd

Hits: 4

(C++ programming Example for Beginners)

C++ Program to Check Whether Number is Even or Odd

In this example, if…else statement is used to check whether a number entered by the user is even or odd.

To understand this example, you should have the knowledge of the following C++ programming topics:

  • C++ if, if…else and Nested if…else

Integers which are perfectly divisible by 2 are called even numbers.

And those integers which are not perfectly divisible by 2 are not known as odd number.

To check whether an integer is even or odd, the remainder is calculated when it is divided by 2 using modulus operator %. If remainder is zero, that integer is even if not that integer is odd.


Example 1: Check Whether Number is Even or Odd using if else


#include <iostream>
using namespace std;

int main(){
    int n;

    cout << "Enter an integer: ";
    cin >> n;

    if ( n % 2 == 0)
        cout << n << " is even.";
    else
        cout << n << " is odd.";

    return 0;
}

Output

Enter an integer: 23
23 is odd.

In this program, if..else statement is used to check whether n%2 == 0 is true or not. If this expression is true, n is even if not n is odd.

You can also use ternary operators ?: instead of if..else statement. Ternary operator is short hand notation of if…else statement.


Example 2: Check Whether Number is Even or Odd using ternary operators


#include <iostream>
using namespace std;

int main(){
    int n;

    cout << "Enter an integer: ";
    cin >> n;
    
    (n % 2 == 0) ? cout << n << " is even." :  cout << n << " is odd.";
    
    return 0;
}

 

C++ for Beginners: C++ Program to Check Whether Number is Even or Odd

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.