To check if a number is even or odd, we divide the number by 2. This is how we can also check if a number is even or odd using the C++ programming language. In this article, I'll walk you through how to write a C++ program to check for odd and even numbers.
C++ Program to Check Odd and Even Numbers
To check if a number is even or odd we need to divide the number by 2, if the remainder we get after dividing the number by 2 is zero then the number is even and if the remainder we get after dividing the number by 2 is not zero then the number is odd. This is the logic we need to use to check if a number is odd or even. So here is how we can write a program to check if a number is odd or even using C++:
In the code above, I first introduced a variable as n, then I took a user input as n which accepts a number from the user. Then I divided the number by 2 using the modulo operator as it gives the remainder as an output. If the remainder is 0, we will get even as the output and if the remainder is not 0, we will get odd as the output.
Summary
This is how we can write a C++ program to check if a number is odd or even. To check if a number is even or odd we need to divide the number by 2, if the remainder we get after dividing the number by 2 is zero then the number is even and if the remainder we get after dividing the number is not equal to zero then the number is odd. Hope you liked this article on how to write a C++ program to check if a number is odd or even. Please feel free to ask your valuable questions in the comments section below.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.