C++ odd even number programs

Here we will find out even or odd numbers in C++ Given by the user to perform this task we used if statement.

We know that those numbers which are completely divided by 2 are called even numbers meaning the remainder is 0 and those that do not divide completely are called odd numbers.

So the condition here will be something like this,

for even number

number%2 == 0

for odd number

number%2 != 0

We will use either of these two conditions in the program here.

find out even or odd numbers in C++

#include<iostream>
using namespace std;
 int main() 
 {
   clrscr();
   int num;  //variable declaration

     cout<<"Enter a number:"; cin>>num;

     cout<<endl;

       if(num%2==0)      // expression
           cout<<num<<" is even number"; // body of if

      else

      cout<<num<<" is odd number";// body of else

return 0;
}

OUTPUT

1st execution

Enter a number: 4
  4 is even number

2nd execution

 Enter a number: 3
 3 is odd number

Explanation:

In first execution user input is 4 which will store in variable number

number = 4

After this, the condition will be checked in the if statement, such as

4%2==0

Because remainder is 0. means the condition is becoming true, the body of if will be execute

In 2nd execution user input is 3

number =3

And as such, the condition will be checked after this

3%2==1.5

And because the remainder is not 0, means the condition is becoming false, the body of if will be skipped and the body of else will be executed.

Thus the program successfully executed.

we can also use both conditions such as,

if(num%2!=0) 
   cout<<"Given number is odd";

else if(num%2==0) 
   cout<<"Given number is even";

C++ Examples

Like it?

Leave a Reply

Your email address will not be published.