Open In App

Shell Script to print odd and even numbers

In this article, we will discuss how to print even and odd numbers. We will take a number as input and print all even and odd numbers from 1 to the number.

Input : Enter the Number – 10



Output : Even Numbers – 2, 4, 6, 8, 10  &  Odd Numbers – 1, 3, 5, 7, 9

Input : Enter the Number – 5



Output : Even Numbers –  2, 4 & Odd Numbers – 1, 3, 5

The approach is that we will divide it in 2. If the remainder is zero, it is an even number, else it is an odd number.

Explaining the code: 

while  [ $i -le $n ]    –  Here “-le” is a comparison operator indicating less than or equal to.

`expr $i % 2`  here “expr” is used to do arithmetic operations and is used with back tick(~)

Code:

# Take user input
echo "Enter a number"
read n

echo "Even Numbers - "
i=1

# -le means less than or equal to
while [ $i -le $n ]
do
# arithmetic operations is performed with 'expr'
rs=`expr $i % 2`

if [ $rs == 0 ]
then
echo " $i"

# end of if loop
fi

# incrementing i by one
((++i))

# end of while loop
done

# Now printing odd numbers
echo "Odd Numbers - "
i=1

while [ $i -le $n ]
do

rs=`expr $i % 2`

if [ $rs != 0 ]
then

echo " $i"

fi

((++i))
done

Output:

Article Tags :