Open In App

Shell Script to print odd and even numbers

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  • Taking input from the user, and loop till we reach the number 

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

  • Then we will check whether it is divisible by 2.

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

  • If the loop is used to check if the remainder is equal to zero, if true it will print an even number, fi indicate the end of if loop.
  • A similar process is for odd numbers.

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:


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads