DEV Community

Its Aomi
Its Aomi

Posted on • Updated on

A Simple C++ Odd or Even Checker

Making a simple C++ Odd or Even Checker.

For more Source Codes visit here.

Create the basic c++ program format using header file iostream and namespace std.

#include <iostream>
using namespace std;

int main() 
{
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

After this create a integer variable n, and output a message and let the user enter a number.

   int n;
   cout<<"Enter number: ";
   cin>>n;
Enter fullscreen mode Exit fullscreen mode

Now using if and else we will see whether the entered number is divisible by two, if it is then its a even number otherwise an odd number.

   if(n%2==0)
     cout<<n<<" It is an Even Number";
   else
     cout<<n<<" It is an Odd Number";
Enter fullscreen mode Exit fullscreen mode

You can now complete the program and run it in any compiler to check its working.

#include <iostream>
using namespace std;

int main() 
{
   int n;
   cout<<"Enter number: ";
   cin>>n;
   if(n%2==0)
     cout <<n<< "\nIt is an Even Number";
   else
     cout <<n<< "\nIt is an Odd Number";
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

Discussion (5)

Collapse
lukeshiru profile image
Luke Shiru

Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:

code block with no colors example

... to specify the language:

code block with colors example

Here's an example using cpp as a language and one of your snippets:

#include <iostream>
using namespace std;

int main() 
{
    int number;
    cout << "Enter number: ";
    cin >> number;
    if (number % 2 == 0)
        cout << number << "\nIt is an Even Number";
    else
        cout << number << "\nIt is an Odd Number";
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

More details in our editor guide!

Now, about the actual code, you can simplify it a little using a ternary:

#include <iostream>
using namespace std;

int main() 
{
    int number;
    cout << "Enter number: ";
    cin >> number;
    cout << number << (number % 2 == 0 ? " is even" : " is odd") << endl;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
itsaomi profile image
Its Aomi Author

Thanks, I am new to dev.to, so I have lots to learn.

Collapse
pauljlucas profile image
Paul J. Lucas

You're missing the \n at the end of the last two cout statements. And please use whitespace around <<.

Collapse
itsaomi profile image
Its Aomi Author

Thanks, its fixed now.

Collapse
khase231 profile image
Khase

Thanks.