0% found this document useful (0 votes)
11 views7 pages

LSP Exp-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views7 pages

LSP Exp-4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Experiment - 4

4. Shell Programming - Looping- while, until, for loops


4.1 Write a shell script to print all even and odd number from 1 to 10.

#!/bin/bash #!/bin/bash
echo "Even numbers are: " echo "Odd numbers are: "
i=1 i=1
while [ $i -le 10 ] while [ $i -le 10 ]
do do
j=`expr $i % 2` j=`expr $i % 2`
if [ $j == 0 ] if [ $j != 0 ]
then then
echo "$i" echo "$i"
fi fi
# increment operator # increment operator
((++i)) ((++i))
done done
Write a shell script to check even and odd number.

#!/bin/bash
echo "enter n value as range to calculate odd and even numbers."
read n
i=1
while [ $i -le $n ]
do
if [ `expr $i % 2` -eq 0 ]
then
echo even=$i
else
echo odd=$i
fi
i=`expr $i + 1`
done
4.2 Write a shell script to print table of a given number.

#!/bin/bash
echo "Enter a Number"
read n
i=1
while [ $i -le 10 ]
do
echo " $n x $i = $(( n * i ))"
i=$(( i + 1 ))
done
4.3 Write a shell script to calculate factorial of a given number.

#!/bin/bash
echo "Enter a number"
read n
f=1
while [ $n -gt 1 ]
do
f=$((f * n)) #f = f * n
n=$((n - 1)) #n= n - 1
done
echo $f
4.4 Write a shell script to print sum of all even numbers from 1 to 10.

#!/bin/bash
echo “Enter number limit"
read n
i=2
while [ $i -lt $n ]
do
sum=$((sum + i))
i=$((i + 2))
done
echo “Total sum: "$sum
done
4.5 Write a shell script to print sum of digit of any number.

#!/bin/bash
echo -n "Enter number : "
read n
# store single digit
sd=0
# store number of digit
sum=0
# use while loop to calculate the sum of all digits
while [ $n -gt 0 ]
do
sd=$(( $n % 10 )) # get Remainder
n=$(( $n / 10 )) # get next digit
sum=$(( $sum + $sd )) # calculate sum of digit
done
echo "Sum of all digit is $sum"

You might also like