Program to check whether a number is divisible by 2 or not in C/C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code
  4. Download Code


To copy code: Click  View Source “View Source” on the right of this code snippet.

Background and Explanation of the code

This program checks whether a number is divisible by ‘2’ or not by using the modulus (%) operator that returns the remainder when a number is divided by the other number. Thus we check whether a number is divisible by ‘2’ by simply checking  whether that number when divided by ‘2’ yields 0 remainder. If it yields ‘0’ then the number is divisible by ‘2’ otherwise it is not.

Some important points for beginners:

1. For division operator C++ provides a modular division operator. This operator returns the remainder on dividing one integer with another. Thus the expression 6/2 yields 3 whereas 6%2 yields ‘0’.

2. Note that that the modulus operator (%) cannot be applied on a float.

3. Also note that on using % the sign of the remainder is always same as the sign of the numerator. Thus -5%2 yields -1 whereas 5%-2 yields 1.

4. On the other hand we have used the decision control statement (if).

The general form of if statement looks like this:
if (this statement is true)
execute this statement;

The keyword ‘if’ tells the compiler that what follows is the decision control instruction. The condition following the keyword ‘if’ is always enclosed within the pair of parenthesis. If the condition ,whatever it is, is true then the statement is executed. If the condition is not true, then the statement is not executed ; instead the program skips past it.

5. The ‘if’ statement by itself will execute a single statement or a group of statements,when the expression following the ‘if’ evaluates to true. It does nothing when the expression evaluates to false. This is what the purpose of the ‘else’ statement that demonstrated in the above program.

6. The group of statements after the ‘if’ upto and not including the ‘else’ is called an ‘if block’. Similarly , the statements after the ‘else’ form is called ‘else block’.

7. Notice that ‘else’ is written exactly below ‘if’ .

On execution of the program the output is shown:

Enter any number:(press any number from the keyboard)
The number is divisible by 2