1. Create a Linux script that asks the user for a number N and prints the sum of
ID: 3674731 • Letter: 1
Question
1. Create a Linux script that asks the user for a number N and prints the sum of thenumbers 1 to N.
2. Modify the previous program such that only multiples of three or five areconsidered in the sum, (e.g. 3, 5, 6, 9, 10, 12, 15 for N=17).
3. Write a Linux script that tests whether a string is a palindrome. (A palindrome is aword, phrase, number, or other sequence of characters which reads the same backward orforward.)
4. Create a Linux script that converts a decimal number A in it's binary, octal andhexadecimal formats and displays them on the screen.
5. Write a Linux script that rotates a list by k elements. For example [1,2,3,4,5,6]rotated by two becomes [3,4,5,6,1,2]. Try solving this without creating a copy of thelist. How many swap or move operations do you need?
6. Write a Linux script that reads two integer numbers A and B then:A) [5p] Computes their Greatest Common Divisor (GCD)B) [5p] Computes their Lowest Common Multiple (LCM)
Explanation / Answer
Please find the answers below :
1)
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
exit 1
fi
n=$1
sum=0
for ((i=1;i<=n;i++)); do
sum = sum + $i
done
echo "Sum is $sum"
2)
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
exit 1
fi
n=$1
sum=0
for ((i=1;i<=n;i++)); do
if [ `echo "$i % 3" | bc` -eq 0 -a `echo "$i % 5" | bc` -eq 0]
sum = sum + $i
done
echo "Sum is $sum"
3)
echo "enter the string "
read name
name1=$(echo $name | rev) #modified version or alternative to ``
if [ $name = $name1 ]
then
echo "**$name is palindrome**"
else
echo "**$name is not a palindrome**"
fi
4)
echo " enter the decimal number"
read n
b = $n;
bin=0
while [ $b -ne 0 ]
do
r=`expr $b%2|bc`
b=`expr $b/2|bc`
bin=$r$bin
done
bin=`expr $bin/10|bc`
echo "The hexadecimal no. is $bin"
hex=`echo "ibase=10;obase=16;$n"|bc`
echo "The hexadecimal no. is $hex"
oct=`echo "ibase=10;obase=8;$n"|bc`
echo "The octal no. is $oct"
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.