Shell_Script_Programs_Algorithms
Shell_Script_Programs_Algorithms
1) Odd or Even
Algorithm:
1. Start.
2. Input a number.
3. If number % 2 == 0, print 'Even'; else print 'Odd'.
4. Stop.
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
if [ $(($num % 2)) -eq 0 ]
then
echo "$num is even."
else
echo "$num is odd."
fi
2) Prime or Not
Algorithm:
1. Start.
2. Input number.
3. If num < 2, print 'Not Prime'.
4. Loop i=2 to sqrt(num): if num % i == 0, print 'Not Prime' and exit. Else, print 'Prime'.
5. Stop.
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
if [ $num -lt 2 ]
then
echo "$num is not a prime number."
exit 0
fi
for (( i=2; i*i<=num; i++ ))
do
if [ $(($num % i)) -eq 0 ]
then
echo "$num is not a prime number."
exit 0
fi
done
echo "$num is a prime number."
Shell Script:
#!/bin/bash
echo "Enter 1st number"
read num1
echo "Enter 2nd number"
read num2
sum=$(($num1 + $num2))
echo "The sum of $num1 and $num2 is $sum."
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
sum=0
temp=$num
while [ $temp -ne 0 ]
do
digit=$(($temp % 10))
sum=$(($sum + $digit))
temp=$(($temp / 10))
done
echo "The sum of digits is $sum."
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
if [ $num -gt 0 ]
then
echo "$num is positive."
elif [ $num -lt 0 ]
then
echo "$num is negative."
else
echo "The number is zero."
fi
6) Divisible by 2, 3 or 5
Algorithm:
1. Start.
2. Input number.
3. Check divisibility for 2, 3, 5 and print accordingly.
4. Stop.
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
if [ $(($num % 2)) -eq 0 ]; then echo "$num is divisible by 2."; fi
if [ $(($num % 3)) -eq 0 ]; then echo "$num is divisible by 3."; fi
if [ $(($num % 5)) -eq 0 ]; then echo "$num is divisible by 5."; fi
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
if [ $num -ge 1 ] && [ $num -le 10 ]
then
echo "$num is between 1 and 10."
elif [ $num -ge 11 ] && [ $num -le 20 ]
then
echo "$num is between 11 and 20."
elif [ $num -ge 21 ] && [ $num -le 30 ]
then
echo "$num is between 21 and 30."
else
echo "$num is not between 1 and 30."
fi
8) Sum of N Numbers
Algorithm:
1. Start.
2. Input N.
3. Sum = 0.
4. Loop i=1 to N: sum += i.
5. Print sum.
6. Stop.
Shell Script:
#!/bin/bash
echo "Enter the value of N"
read n
sum=0
for (( i=1; i<=n; i++ ))
do
sum=$(($sum + $i))
done
echo "The sum of first $n numbers is $sum."
Shell Script:
#!/bin/bash
sum=0
for (( i=1; i<=10; i++ ))
do
sum=$(($sum + $i))
done
echo "The sum of first 10 numbers is $sum."
Shell Script:
#!/bin/bash
echo "Enter a number"
read num
fact=1
for (( i=1; i<=num; i++ ))
do
fact=$(($fact * $i))
done
echo "The factorial of $num is $fact."