It is simple to find given number is even or odd manually if it is small or less than 1000. If the given number is greater than 1000 it is not so easy to say a number is even or odd. Therefore today we shall write a script to find given number even or odd. BY definition a number is even if the remainder of the division of the number by 2 is zero. IF it is not zero it is called as odd. In program we shall use the modulus operator % to find the remainder of the division. As input we shall ask for number from the user.In order to check whether the remainder is zero or some-other we shall use the if else statement.The syntax of the if else statement is:
if [ expr ]
then
//expression to be evaluated
else
//expression to be evaluated
fi
Every ‘if’ statement should be end by ‘end fi’ statement.In the expr of if statement if we need to compare the two numbers we use the following codes:
- For equal to: -eq
- For less-than:-lt
- For greater than:-gt
- For less than or equal to:-le
- For greater than or equal to:-ge
The script is:
echo “Enter any value for n:”
read n
a = `expr $n % 2`
if [ $a -eq 0 ]
then
echo “Given number $n is even”
else
echo “Given number $n is odd”
fi
output:
Enter the value of the n:5
Given number 5 is odd