shell script to find given number even or odd

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:

  1. For equal to: -eq
  2. For less-than:-lt
  3. For greater than:-gt
  4. For less than or equal to:-le
  5. For greater than or equal to:-ge
  6. 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

    Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Shell scripting and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s