Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

University of Calcutta

B.Sc. Semester II (Hons.)


Examination - 2023 (Under CBCS)

Roll No: 213223 – 21 – 0059


Reg. No: 223 - 1111 - 0312 - 21

Subject: CMSA Paper: CMS-A-CC-3-7-P


(Operating Systems Lab.)
1

Serial Date Content Page No. Signature


No.
1 20/08/2022 Write a menu driven program to 3-5
accept two integers and perform the
four basic arithmetic calculations
addition, subtraction, multiplication
and division using functions.

2 25/08/2022 Find the sum of the following 6-8


series:
a. 1+2+3+.......+n
b. 1+(1+2)+(1+2+3)+ … +
(1+2+3+.....+n)

3 03/09/2022 Generate all the Armstrong 9 - 11


numbers within a user given range
through command line arguments.

4 06/09/2022 Print the following patterns: 12 - 15


a.
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
b.
*
* *
* * *
* * * *
* * * * *
c.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

5 06/09/2022 Calculate the factorial of a number 16 - 17


using functions.

6 07/09/2022 Simulate the wc command with its 18 - 20


options -l, -w and -c

7 13/09/2022 Input an array of integers and find 21 - 22


out the maximum and minimum
value.
2

8 14/09/2022 Sort an array of elements in 23 - 24


descending order using Bubble Sort
mechanism.

9 27/09/2022 Check whether a given integer or a 25 - 26


string is a palindrome or not using
separate functions.

10 27/09/2022 Display all the integer palindromes 27 - 28


within a user given range through
command line arguments.

11 28/09/2022 Accept a password and check 29 - 30


whether it is strong or a weak one.

12 29/10/2022 Input the percentage marks of a 31 - 32


student and print the grade
accordingly using case:
90 to 100 – Outstanding
60 to 89 – Excellent
40 to 59 – Good
Less than 40 – Try Again

13 29/20/2022 Find out the n-th term of the 33 - 34


Fibonacci series.

14 01/11/2022 Check whether a given number 35 - 36


through command line argument is
prime or composite.

15 03/11/2022 Use functions to find the HCF and 37 - 39


LCM of two numbers.

16 05/11/2022 Input two integer matrices and 40 - 43


perform matrix addition.

17 01/12/2022 Input two integer matrices and 44 - 47


perform matrix multiplication.

18 03/12/2022 Accept an array of integers and 48 - 51


perform linear and binary search
using separate functions.
3

20/08/2022
Assignment 1: Write a menu driven program to accept two integers and perform the four
basic arithmetic calculations addition, subtraction, multiplication and division using functions.

Algorithm:

a) Addition( a, b )
Adds the numbers a and b

Begin
set a variable sum to (a + b)
return sum
End

b) Subtraction( a, b )
Subtracts the numbers a and b

Begin
set a variable sub to (a - b)
return sub
End

c) Mult( a, b )
Multiplies the numbers a and b

Begin
set a variable mul to (a * b)
return mul
End

d) Div( a, b )
Divides the numbers a and b

Begin
set a variable div to (a / b)
return div
End

Implementation in Shell

#!/bin/bash

# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------
4

addition() {
sum=`expr $1 + $2`
echo $sum
}

subtraction() {
diff=`expr $1 - $2`
echo $diff
}

multiplication() {
prod=`expr $1 \* $2`
echo $prod
}

division() {
quot=`echo "scale=2;($1/$2)"|bc`
echo $quot
}
read -p "Enter 1st number " a
read -p "Enter 2nd number " b
echo "Enter 1 to perform Addition"
echo "Enter 2 to perform Subtraction"
echo "Enter 3 to perform Multiplication"
echo "Enter 4 to perform Division"
read -p "Enter your choice " op

case $op in
1)
x=$(addition $a $b)
echo "The sum is: $x"
;;

2)
x=$(subtraction $a $b)
echo "The difference is: $x"
;;

3)
x=$(multiplication $a $b)
echo "The product is: $x"
;;

4)
x=$(division $a $b)
echo "The division is: $x"
5

;;

*)
echo "Invalid input"
esac

Output Sets

➜ assignments ./ass1.sh
Enter 1st number 13
Enter 2nd number 56
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 1
The sum is: 69

➜ assignments ./ass1.sh
Enter 1st number 56
Enter 2nd number 34
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 2
The difference is: 22

➜ assignments ./ass1.sh
Enter 1st number 44
Enter 2nd number 66
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 3
The product is: 2904

➜ assignments ./ass1.sh
Enter 1st number 48
Enter 2nd number 31
Enter 1 to perform Addition
Enter 2 to perform Subtraction
Enter 3 to perform Multiplication
Enter 4 to perform Division
Enter your choice 4
The division is: 1.54
6

25/08/2022
Assignment 2: Find the sum of the following series:
a. 1+2+3+.......+n
b. 1+(1+2)+(1+2+3)+.......(1+2+3+.....+n)

Algorithm:
a) Begin
read num from the user
set sum = n * (n + 1) / 2
print sum
End

b) Begin
read num from the user
set i to 0
while i <= num do
set j=1
while j <= i do
set sum = sum + j
set j = j + 1
end of while
I=i+1
end of while
End

Implementation in Shell

a)

#!/bin/bash

# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
n=$1
if [ $n -le 0 ]; then
echo "Invalid argument"
exit 1
fi
# Main code
sum=0
7

# For iterative approach

# for (( i=1 ; i<=$n ; i++ )); do


# sum=$(( $sum+$i ))
# done

# Uncomment if you like


sum=$(( ($n*($n+1))/2 ))
# ---------------------

echo "The sum of natural numbers up until $n is $sum"

else
echo "Not enough arguments"
fi

Output Sets

➜ assignments ./ass2a.sh
Not enough arguments
➜ assignments ./ass2a.sh 20
The sum of natural numbers up until 20 is 210
➜ assignments ./ass2a.sh -1
Invalid argument

b)

#!/bin/bash

# ----------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ----------

if [ $# -ge 1 ]; then
n=$1
if [ $n -le 0 ]; then
echo "Invalid argument"
exit 1
fi
# Main code
i=1
sum=0
while [ $i -le $n ]; do
j=1
while [ $j -le $i ]; do
8

sum=`expr $sum + $j`


j=`expr $j + 1`
done
i=`expr $i + 1`
done

echo "The Sum of the Series= " $sum

else
echo "Not enough arguments"
fi

Output Sets

➜ assignments ./ass2b.sh
Not enough arguments
➜ assignments ./ass2b.sh 2
The Sum of the Series= 4
➜ assignments ./ass2b.sh 20
The Sum of the Series= 1540
➜ assignments ./ass2b.sh -1
Invalid argument
9

03/09/2022
Assignment 3: Generate all the Armstrong numbers within a user given range through
command line arguments.

Algorithm

Step 1: Begin
Step 2: armstrong():
1. Set num:=argument 1, temp:=num, sum:=0, count:=0
2. while temp>0 do
Set count:=count+1
Set temp:=temp/10
3. done
4. Set temp:=num
5. while num>0 do
Set d:=num%10
Set sum:=sum+(d to the power of count)
Set num:=num/10
6. done
7. if sum=temp then
Return 0
8. Else,
Return 1
9. End of if
Step 3: Set lowerlimit:=argument 1, upperlimit:=argument 2
Step 4: for i:= lowerlimit to upperlimit step +1 do
1. Calling armstrong() with i as parameter
2. Set res:=value returned by armstrong()
3. if res=0 then
Print(i)
4. End of if
Step 5: done
Step 6: End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

arms() {
aNum=$1
10

aNumC=$aNum # Copy of the number

# Count the number of digits

aNumDig=0 # Store number of digits

while [ $aNumC -gt 0 ]; do


aNumC=$(( $aNumC / 10 ))
aNumDig=$(( $aNumDig + 1)) # calculate all digit in a
number till n is not zero
done

# Calculating if Armstrong
aNumC=$aNum # Reinitializing the copy value
aSum=0
while [ $aNumC -gt 0 ]; do
aRemain=$(( $aNumC%10 ))
aExp=$(( $aRemain**$aNumDig ))
aSum=$(( $aSum+$aExp ))
aNumC=$(( $aNumC/10 ))
done

if [ $aSum -eq $aNum ]; then


return 0
else
return 1
fi
}

# Arguments exception handling


if [ $# -ne 2 ]; then
echo "Incorrect number of arguments"
exit 1
fi

lowerLim=$1
upperLim=$2

# Checking if the values are correct


if [ $lowerLim -ge $upperLim ]; then
echo "Please enter the lower limit as the first and upper
limit as the second argument"
exit 1
fi

# Eliminating zero as lower limit


11

if [ $lowerLim -eq 0 ]; then


lowerLim=$(( $lowerLim+1 ))
fi

for (( i=$lowerLim; i<=$upperLim; i++ )); do


arms $i
isArms=$?
if [ $isArms -eq 0 ]; then
echo $i
fi
done

Output Sets

➜ assignments ./ass3.sh
Incorrect number of arguments
➜ assignments ./ass3.sh 100 200
153
➜ assignments ./ass3.sh 100 1000
153
370
371
407
➜ assignments ./ass3.sh 1000 5000
1634
➜ assignments ./ass3.sh 1000
Incorrect number of arguments
12

06/09/2022
Assignment 4: Print the following patterns:
a.
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
b.
*
* *
* * *
* * * *
* * * * *
c.
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Algorithm

a) Pattern1( n )
Here n is the dimension of the pattern
Begin
for i:=1 to n do
for i:=1 to n do
if j >= i then
print j
else
print space
end if
print space
end of for
go to new line
end of for
End
b) Pattern2 ( n )
Begin
for i:=1 to n step +1 do
Set k:=0
for space:=1 to (n-i) step +1 do
Print “ ”
done
while k not equal to i do
13

Print “*”
Set k:=k+1
done
done
End

c) Pattern3 ( n )
Begin
Set coef:=1
for i:=1 to n-1 step +1 do
for space:=1 to (n-i) step +1 do
Print “ ”
done
for j:=0 to i step +1 do
if j=0 or i=0 then
Set coef:=1
else,
Set coef:=coef*(i-j+1)/j
End of if
Print(coef)
done
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science,
# Scottish Church College, Kolkata
# ------------

if [ $# -ne 2 ]; then
echo "Not enough args. Format: ./pattern.sh dimension case"
exit
fi

n=$1
choice=$2

pattern1 () {
for (( i=1; i<=n; i++ )) {
for (( j=1; j<=$n; j++ )) {
if [ $j -ge $i ]; then
echo -n $j
else
echo -n " "
14

fi
echo -n " "
}
echo
}
}

pattern2 () {
for (( i=1; i<=$n; i++ )) {
k=0
for (( space=1; space<=$(($n-$i)); space++ )) {
echo -n " "
}

while [ $k -ne $i ]; do
echo -n "* "
k=$(($k+1))
done
echo
}
}

pattern3 () {
coef=1
for(( i=0 ; i<$n ; i++ )); do
for(( space=1 ; space <= $n-$i ; space++ )); do
echo -n " "
done
for(( j=0 ; j<=$i ; j++ )); do
if [ $j -eq 0 -o $i -eq 0 ]; then
coef=1;
else
coef=$(($coef*($i-$j+1)/$j))
fi
echo -n "$coef "
done
echo
done
}

case $choice in
0)
pattern1
;;
1)
pattern2
;;
15

2)
pattern3
;;
*)
esac

Output Sets

➜ assignments ./ass4.sh 4 0
1 2 3 4
2 3 4
3 4
4
➜ assignments ./ass4.sh 5 1
*
* *
* * *
* * * *
* * * * *
➜ assignments ./ass4.sh 5 2
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
➜ assignments ./ass4.sh
Not enough args. Format: ./pattern.sh dimension case
16

06/09/2022
Assignment 5: Calculate the factorial of a number using functions.

Algorithm

Begin
set n:=argument 1, fact:=1
while n>1 do
set fact:=fact*n
set n:=n-1
done
print fact
Stop

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

fact() {
num=$1
if [ $num -eq 0 ]; then
echo 1
return
fi
fact=1
while [ $num -gt 1 ]; do
fact=$(($fact * $num)) #fact = fact * num
num=$(($num - 1)) #num = num - 1
done

echo $fact
}

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
# Main code
n=$1
f=`fact $n`
echo "Factorial of $n is $f"
else
17

echo "Not enough arguments"


fi

Output Sets

➜ assignments ./ass5.sh
Not enough arguments
➜ assignments ./ass5.sh 5
Factorial of 5 is 120
➜ assignments ./ass5.sh 10
Factorial of 10 is 3628800
➜ assignments ./ass5.sh 3
Factorial of 3 is 6
18

07/09/2022
Assignment 6: Simulate the wc command with its options -l, -w and -c

Algorithm

Begin
Execute only if argument 2 is an executable file
Under case block with choice as argument 1,
1.
set nol:=0
while lines present in the file do
set nol:=nol+1
done
print(nol)
Terminating from case block
2.
set now:=0
while lines present in the file do
Accessing all the words in a line
Set now:=now+count of words in a line
done
Print(now)
Terminating from case block
3.
Set noc:=0
while lines present in the file do
Accessing all the words in a line
for words present in the line do
Extracting all the characters from a word and storing in char
Set noc:=noc+char
done
done
Print(noc)
Terminating from case block
4.
Print “Invalid Option”
End of case block
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
19

# ------------

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
# Main code
# Used -wo instead of -w since that's an in built flag
#[$1= -l/-w/-c, $2=filename]
exec<$2
case $1 in
'-l')
nol=0
while read line; do
nol=`expr $nol + 1`
done
echo "Number of lines is $nol"
;;

'-w')
now=0
while read line; do
set $line
now=`expr $now + $#`
done
echo "Number of words is $now"
;;
'-c')
while read line; do
set $line
for word in $*; do
char=`expr length $word`
noc=`expr $noc + $char`
done
done
echo "Number of characters is $noc"
;;
*)
echo "Invalid Option"
;;
esac

else
echo "Not enough arguments"
fi
20

Output Sets

➜ assignments ./ass6.sh -l ass6.sh


Number of lines is 50
➜ assignments ./ass6.sh -c ass6.sh
Number of characters is 111
➜ assignments ./ass6.sh -w ass6.sh
Number of words is 141
21

13/09/2022
Assignment 7: Input an array of integers and find out the maximum and minimum value.

Algorithm

Begin
Dynamically accepting input in the array a
Set min:=1 st element of a, max:=1 st element of a
for i:=through all the elements of a do
if i<min then
Set min:=i
End of if
if i>max then
max:=i
End of if
done
Print(min) and Print(max)
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

echo "Enter your values, type Ctrl+D when done"

while read line; do


a=("${a[@]}" $line)
done

min=${a[0]}
max=${a[0]}

for i in ${a[@]}; do
if [ $i -lt $min ]; then
min=$i
fi
if [ $i -gt $max ]; then
max=$i
fi
done
22

echo "Min: $min"


echo "Max: $max"

Output Sets

➜ assignments ./ass7.sh
Enter your values, type Ctrl+D when done
4
34
9
35
2
0
-1
Min: -1
Max: 35
➜ assignments ./ass7.sh
Enter your values, type Ctrl+D when done
-10000
3
-20
-90
Min: -10000
Max: 3
23

14/09/2022
Assignment 8: Sort an array of elements in descending order using Bubble Sort
mechanism.

Algorithm

Begin
Dynamically accepting input in the array a
Set n:=number of elements in a
for i:=1 to n-1 step +1 do
for j:=1 to n-i-1 step +1 do
if j-th element<(j+1)th element of a then
Set temp:=jth element of a
Set jth element:=(j+1)th element of a
Set (j+1)th element:=temp
End of if
done
done
Print(a)
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

read -a arr -p "Enter your values: "


n=${#arr[@]}

for ((i=0; i<$n; i++)); do


for ((j=$i; j<$n; j++)); do
if [ ${arr[$i]} -lt ${arr[$j]} ]
then
temp=${arr[$i]}
arr[$i]=${arr[$j]}
arr[$j]=$temp
fi
done
done

echo "Sorted array: ${arr[@]}"


24

Output Sets

➜ assignments ./ass8.sh
Enter your values: 45 78 3 90 45
Sorted array: 90 78 45 45 3
➜ assignments ./ass8.sh
Enter your values: 1 2 3 4 5 67 7 8
Sorted array: 67 8 7 5 4 3 2 1
25

27/09/2022
Assignment 9: Check whether a given integer or a string is a palindrome or not using
separate functions.

Algorithm

Begin
palin():
Set str:=argument 1
Set str1:=reverse of str
if str=str1 then
Print “str is a palindrome”
Else,
Print “str is not a palindrome”
End of if
Read(s)
Calling palin() with s as parameter
Stop

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

# Do it with a/two function

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
# Main code
str=$1
# p=`palin $str`
a=`echo $1 | rev`
# echo $a

if [ "$str" == "$a" ]; then


echo "$str is a palindrome"
else
echo "$str is not a palindrome"
fi

else
26

echo "Not enough arguments"


fi

Output Sets

➜ assignments ./ass9.sh scottish


scottish is not a palindrome
➜ assignments ./ass9.sh scottocs
scottocs is a palindrome
➜ assignments ./ass9.sh 786364
786364 is not a palindrome
➜ assignments ./ass9.sh 7863687
7863687 is a palindrome
27

27/09/2022
Assignment 10: Display all the integer palindromes within a user given range through
command line arguments.

Algorithm

Begin
palin():
Set str:=argument 1
Set str1:=reverse of str
if str=str1 then
Print “str is a palindrome”
Else,
Print “str is not a palindrome”
End of if
Read upperlimit and lowerlimit
for i:=lowerlimit to upperlimit do
palin(i)
end of for
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

palin() {
str=$1
str1=`echo $str | rev`
if [ "$str" == "$str1" ]; then
echo $str
fi
}

lowerlimit=$1
upperlimit=$2
for (( i=lowerlimit; i<=upperlimit; i++ )); do
palin $i
done
28

Output Sets

➜ assignments ./ass10.sh 1 100


1
2
3
4
5
6
7
8
9
11
22
33
44
55
66
77
88
99
➜ assignments ./ass10.sh 100 200
101
111
121
131
141
151
161
171
181
191
29

28/09/2022
Assignment 11: Accept a password and check whether it is strong or a weak one.

Algorithm

Begin
Define arrays for special characters, numericals, small characters and
capital characters.
Set the arrays to all the related characters
Read password
Set sp, cl, sm, nu to 0
For letter in password do
If letter in specialChars do
sp = 0
End of if
If letter in numericals do
nu = 0
End of if
If letter in smallChar do
sm = 0
End of if
If letter in bigChars do
cl = 0
End of if
Done
Set sum to sp+nu+sm+cl
If sum >= 4 then
Print “Password is strong”
Else
Print “Password is weak”
End of if

End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

specialChars=("! # $ % & ' ( ) \* + , - . / : ; < = > ? @ [ \ ] ^


_ \` { | } ~")
numericals=("0 1 2 3 4 5 6 7 8 9")
30

smallLetters=("q w e r t y u i o p a s d f g h j k l z x c v b n
m")
capitalLetters=("Q W E R T Y U I O P A S D F G H J K L Z X C V B N
M")

read -p "Enter your password: " password


# read -sp for hiding the input

sp=0; cl=0; sm=0; nu=0


score=0

for (( i=0; i<${#password}; i++ )); do


char=${password:$i:1}
if [[ " ${specialChars[*]} " =~ " ${char} " ]]; then
sp=1
fi
if [[ " ${numericals[*]} " =~ " ${char} " ]]; then
nu=1
fi
if [[ " ${smallLetters[*]} " =~ " ${char} " ]]; then
sm=1
fi
if [[ " ${capitalLetters[*]} " =~ " ${char} " ]]; then
cl=1
fi
done
score=$(( sp+nu+sm+cl ))

if [ $score -ge 4 ]; then


echo "Your password is strong"
else
echo "Your password is weak"
fi

Output Sets

➜ assignments ./ass11.sh
Enter your password: scottish1234
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish1234
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish&$#@
Your password is weak
➜ assignments ./ass11.sh
Enter your password: Scottish*&&318943*&
31

Your password is strong


29/10/2022
Assignment 12: Input the percentage marks of a student and print the grade accordingly
using case:
90 to 100 – Outstanding
60 to 89 – Excellent
40 to 59 – Good
Less than 40 – Try Again

Algorithm

Begin
Read(m)
Under case block with choice as m,
90-100:
Print “Outstanding”
Terminating from case block
60-89:
Print “Excellent”
Terminating from case block
40-69:
Print “Good”
Terminating from case block
0-39:
Print “Try Again”
Terminating from case block
Otherwise,
Print “Invalid input”
End of case block
End

Implementation in Shell

#!/bin/bash
# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

read -p "Enter the percentage marks of the student: " marks


if [ $marks -lt 0 ] || [ $marks -gt 100 ]; then
echo "Invalid input"
exit 1
fi
32

case $marks in
[1][0][0])
echo "Outstanding"
;;
[9][0-9])
echo "Outstanding"
;;
[6-8][0-9])
echo "Excellent"
;;
[4-5][0-9])
echo "Good"
;;
[0-3][0-9])
echo "Try again"
;;
*)
echo "Invalid input"
exit 1
esac

Output Sets

➜ assignments ./ass12.sh
Enter the percentage marks of the student: 10
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 56
Good
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 99
Outstanding
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 30
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 34
Try again
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 65
Excellent
➜ assignments ./ass12.sh
Enter the percentage marks of the student: 40
Good
➜ assignments ./ass12.sh
Enter the percentage marks of the student: -87
Invalid input
33

29/10/2022
Assignment 13: Find out the n-th term of the Fibonacci series.

Algorithm
Begin
fibonacci():
Set nf:=argument 1, b:=1, s:=0
for i=:=1 to nf step +1 do
Set s:=s+b
Set b:=s-b
done
Print(s)
Read(n)
if n>0 then,
Calling fibonacci() with n as parameter
else,
Print “Invalid input”
end of if
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

fibonacci() {
nf=$1
s=0
b=1
for(( i=1 ; i<=$nf ; i++ )); do
s=$(($s+$b))
b=$(($s-$b))
done
echo "The n-th term of Fibonacci Series is $s"
}

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
# Main code
n=$1
34

if [ $n -le 0 ]; then
echo "Invalid argument"
exit 1
fi
fibonacci $n

else
echo "Not enough arguments"
fi

Output Sets

➜ assignments ./ass13.sh
Not enough arguments
➜ assignments ./ass13.sh 7
The n-th term of Fibonacci Series is 13
➜ assignments ./ass13.sh 40
The n-th term of Fibonacci Series is 102334155
➜ assignments ./ass13.sh 1
The n-th term of Fibonacci Series is 1
35

1/11/2022
Assignment 14: Check whether a given number through command line argument is prime
or composite.

Algorithm

Begin
isPrime():
Set num:=argument 1
if num=0 then,
Return 1
else if num=1 then,
Return 1
end of if
Set halfNum:=num/2
for i:=2 to halfNum step +1 do
Set m:=num%i
if m=0 then,
Return 1
end of if
done
Return 0

Calling isPrime() with the 1 st argument as a parameter


if the value returned by isPrime() is 0 then,
Print argument 1 as a prime number
else,
Print argument 1 as a composite number
end of if
else,
Print a suitable message for having less than required arguments
end of if
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

isPrime() {
36

num=$1
if [ $num -eq 0 ]; then
return 1
elif [ $num -eq 1 ]; then
return 1
fi
halfNum=$(( $num/2 ))
for (( i=2; i<=$halfNum; i++ )); do
modulo=$(( $num%$i ))
if [ $modulo -eq 0 ]; then
return 1
fi
done
return 0
}

# Checking if there are correct number of args


if [ $# -ge 1 ]; then
# Main code
isPrime $1
if [ $? -eq 0 ]; then
echo "The given number, $1, is a prime"
else
echo "The given number, $1, is composite"
fi

else
echo "Not enough arguments"
fi

Output Sets

➜ assignments ./ass14.sh 14
The given number, 14, is composite
➜ assignments ./ass14.sh 41
The given number, 41, is a prime
➜ assignments ./ass14.sh 2
The given number, 2, is a prime
➜ assignments ./ass14.sh 2657
The given number, 2657, is a prime
37

3/11/2022
Assignment 15: Use functions to find the HCF and LCM of two numbers.

Algorithm

Begin
hcf():
Set a:=argument 1, b:= argument 2
while b not equal to 0 do
Set r:=a%b
Set a:=b, b:=r
done
Return a
lcm():
Set x:=argument 1, y:= argument 2
if x>;y then,
Set max:=x
else,
Set max:=y
end of if
while 1 do
Set p:=max%x, q:=max%y
if p=0 and q=0 then,
Print(max)
Terminate from method
end of if
Set max:=max+1
Done
Read(c)
Under case block with c as choice
1.
Read(n1) and Read(n2)
Calling hcf() with n1 and n2 as parameters
Print the value returned by hcf()
Terminating from case block
2.
Read(n1) and Read(n2)
Calling lcm() with n1 and n2 as parameters
Terminating from case block
3.
Print “Wrong choice”
End of case block
End

Implementation in Shell
38

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

hcf() {
a=$1
b=$2
while [ $b -ne 0 ]
do
r=`expr $a % $b`
a=$b
b=$r
done
return $a #a stores the hcf
}

lcm() {
x=$1
y=$2
if [ $x -gt $y ] #for finding the greater no of the two
then
max=$x
else
max=$y
fi
while [ 1 ]
do
p=`expr $max % $x`
q=`expr $max % $y`
if [ $p -eq 0 -a $q -eq 0 ]
then
echo "LCM is=$max"
break #exits from while loop
fi
max=`expr $max + 1`
done
}
echo "1. HCF"
echo "2. LCM"
echo "Enter your choice"
read c #stores choice
39

case $c in
1)
echo "Enter the first number"
read n1
echo "Enter the second number"
read n2
hcf $n1 $n2
echo "HCF is = $?"
;;
2)
echo "Enter the fist number"
read n1
echo "Enter the second number"
read n2
lcm $n1 $n2
;;
*)
echo "It was a wrong choice"
;;
esac

Output Sets

➜ assignments ./ass15.sh
1. HCF
2. LCM
Enter your choice
1
Enter the first number
34
Enter the second number
56
HCF is = 2
➜ assignments ./ass15.sh
1. HCF
2. LCM
Enter your choice
2
Enter the fist number
56
Enter the second number
2
LCM is=56
40

5/11/2022
Assignment 16: Input two integer matrices and perform matrix addition.

Algorithm

Begin
printMat():
Set matrix := argument 1
Set r:= argument 2, c := argument 3
for j := 0 to r step +1 do
for i := 0 to c step +1 do
Set index := j * c + i
Print matrix[index]
done
done

Read(rows) and Read(cols)


Read the first matrix in one dimensional row major form and set to matrix1
Read the second matrix in one dimensional row major form and set to matrix2

Print matrix1
Print matrix2

Set k := 0
Initialise empty array matrix3
for j := 0 to rows step +1 do
for i := 0 to cols step +1 do
Set index := j * c + i
matrix3[k]=$((${matrix1[index]} + ${matrix2[index]}))
k=$((k+1))
done
done

Print matrix3
End

Implementation in Shell

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------
41

read -p "Enter the number of rows: " rows


read -p "Enter the number of cols: " cols

echo
echo "Input the first matrix"

for ((j = 0; j < $rows; j++)); do


for ((i = 0; i < $cols; i++)); do
read -p "Enter row $j column $i: " matrix1[$((j * $cols +
i))]
done
done

echo
echo "Input the second matrix"

for ((j = 0; j < $rows; j++)); do


for ((i = 0; i < $cols; i++)); do
read -p "Enter row $j column $i: " matrix2[$((j * $cols +
i))]
done
done
echo

echo "The first matrix:"


for((i=0; i<rows; i++))
do
for((j=0; j<cols; j++))
do
index=$((i*cols+j))
echo -n "${matrix1[index]} "
done
echo
done

echo "The second matrix:"


for((i=0; i<rows; i++))
do
for((j=0; j<cols; j++))
do
index=$((i*cols+j))
echo -n "${matrix2[index]} "
done
echo
done

k=0
matrix3=()
42

for((i=0; i<rows; i++))


do
for((j=0; j<cols; j++))
do
index=$((i*cols+j))
matrix3[k]=$((${matrix1[index]} + ${matrix2[index]}))
k=$((k+1))
done
done
echo "Addition of two matrix"
for((i=0; i<rows; i++))
do
for((j=0; j<cols; j++))
do
index=$((i*cols+j))
echo -n "${matrix3[index]} "
done
echo
done

Output Sets

➜ assignments ./ass16.sh
Enter the number of rows: 3
Enter the number of cols: 3

Input the first matrix


Enter row 0 column 0: 1
Enter row 0 column 1: 2
Enter row 0 column 2: 3
Enter row 1 column 0: 4
Enter row 1 column 1: 5
Enter row 1 column 2: 6
Enter row 2 column 0: 7
Enter row 2 column 1: 8
Enter row 2 column 2: 9

Input the second matrix


Enter row 0 column 0: 9
Enter row 0 column 1: 8
Enter row 0 column 2: 7
Enter row 1 column 0: 6
Enter row 1 column 1: 5
Enter row 1 column 2: 4
Enter row 2 column 0: 3
Enter row 2 column 1: 2
Enter row 2 column 2: 1
43

The first matrix:


1 2 3
4 5 6
7 8 9
The second matrix:
9 8 7
6 5 4
3 2 1
Addition of two matrix
10 10 10
10 10 10
10 10 10
➜ assignments ./ass16.sh
Enter the number of rows: 2
Enter the number of cols: 3

Input the first matrix


Enter row 0 column 0: 5
Enter row 0 column 1: 3
Enter row 0 column 2: 8
Enter row 1 column 0: 65
Enter row 1 column 1: 3
Enter row 1 column 2: 7

Input the second matrix


Enter row 0 column 0: 3
Enter row 0 column 1: 5
Enter row 0 column 2: 8
Enter row 1 column 0: 2
Enter row 1 column 1: 5
Enter row 1 column 2: 7

The first matrix:


5 3 8
65 3 7
The second matrix:
3 5 8
2 5 7
Addition of two matrix
8 8 16
67 8 14
44

1/12/2022
Assignment 17: Input two integer matrices and perform matrix multiplication.

Algorithm

Begin
printMat():
Set matrix := argument 1
Set r:= argument 2, c := argument 3
for j := 0 to r step +1 do
for i := 0 to c step +1 do
Set index := j * c + i
Print matrix[index]
done
done

Read(r1) and Read(c1)


Read(r2) and Read(c2)

if c1 is not equal to r2 then


Prompt “Multiplication is not possible”
Exit the script
end of if

Read the first matrix in one dimensional row major form and set to matrix1
Read the second matrix in one dimensional row major form and set to matrix2

Print matrix1
Print matrix2

Initialise empty array matrix3


for j := 0 to rows step +1 do
for i := 0 to cols step +1 do
Set index := i * c2 + j
for k := 0 to r2 step +1 do
Set idx1 := i * c2 + k
Set idx2 := k * c2 + j
Set matrix3[index] := matrix1[idx1] + matrix2[idx2]
done
done
done

Print matrix3
End

Implementation in Shell
45

#!/bin/bash

# ------------
# Author: Bhaswar Chakraborty
# Department of Computer Science
# Scottish Church College, Kolkata
# ------------

read -p "Enter the number of rows of the first matrix: " R1


read -p "Enter the number of cols of the first matrix: " C1
read -p "Enter the number of rows of the second matrix: " R2
read -p "Enter the number of cols of the second matrix: " C2

echo

if [ $C1 -ne $R2 ]; then


echo "Invalid. Matrix multiplication is not possible."
exit 0
fi

echo "Input the first matrix"

for ((j = 0; j < $R1; j++)); do


for ((i = 0; i < $C1; i++)); do
read -p "Enter row $j column $i: " matrix1[$((j * $C1 +
i))]
done
done

echo
echo "Input the second matrix"

for ((j = 0; j < $R2; j++)); do


for ((i = 0; i < $C2; i++)); do
read -p "Enter row $j column $i: " matrix2[$((j * $C2 +
i))]
done
done
echo

echo "The first matrix:"


for((i=0; i<R1; i++))
do
for((j=0; j<C1; j++))
do
index=$((i*C1+j))
echo -n "${matrix1[index]} "
46

done
echo
done

echo "The second matrix:"


for((i=0; i<R2; i++))
do
for((j=0; j<C2; j++))
do
index=$((i*C2+j))
echo -n "${matrix2[index]} "
done
echo
done

k=0
matrix3=()
for((i=0; i<R1; i++))
do
for((j=0; j<C2; j++))
do
index=$((i*C2+j))
sum=0
for((k=0; k<R2; k++)); do
idx1=$((i*C1+k))
idx2=$((k*C2+j))
mul=$((${matrix1[idx1]} * ${matrix2[idx2]}))
sum=$(($sum + $mul))
done
matrix3[index]=$sum
done
done
echo "Multiplication of two matrix"
for((i=0; i<R1; i++))
do
for((j=0; j<C2; j++))
do
index=$((i*cols+j))
echo -n "${matrix3[index]} "
done
echo
done

Output Sets

➜ assignments ./ass17.sh
Enter the number of rows of the first matrix: 3
Enter the number of cols of the first matrix: 2
47

Enter the number of rows of the second matrix: 2


Enter the number of cols of the second matrix: 3

Input the first matrix


Enter row 0 column 0: 1
Enter row 0 column 1: 1
Enter row 1 column 0: 2
Enter row 1 column 1: 2
Enter row 2 column 0: 3
Enter row 2 column 1: 3

Input the second matrix


Enter row 0 column 0: 1
Enter row 0 column 1: 1
Enter row 0 column 2: 1
Enter row 1 column 0: 2
Enter row 1 column 1: 2
Enter row 1 column 2: 2

The first matrix:


1 1
2 2
3 3
The second matrix:
1 1 1
2 2 2
Multiplication of two matrix
3 3 3
6 6 6
9 9 9
➜ assignments ./ass17.sh
Enter the number of rows of the first matrix: 1
Enter the number of cols of the first matrix: 2
Enter the number of rows of the second matrix: 4
Enter the number of cols of the second matrix: 2

Invalid. Matrix multiplication is not possible.


48

3/12/2022
Assignment 18: Accept an array of integers and perform linear and binary search using
separate functions.

Algorithm

Begin
Step 1: Input the length of array
Step 2: Input the elements of the array
Step 3: Input the number to searched
Step 4: linear_search()
1. Variable i is initialised to 0 for traversing the array
2. Begin while(i < length of array) loop
- Check if current element is equal to the element being searched, if
true, ret=i and return
- Increment i by 1
3. ret=-1 (element not found)
Step 5: selection_sort()
1. Initialise i with 0 for outer loop
2. Begin outer loop while(i < length of array)
- Initialise j with i+1 for inner loop
- Begin inner loop while(j < length of array)
- if element at j is less than element at i, swap elements
- Increment j by 1
- Increment i by 1
Step 6: binary_search()
1. Initialise lower with 0 and upper with length of array - 1
2. Begin loop while( lower <= upper)
- Declare mid with (lower+upper)/2
- If element at mid equals element being searched, ret=mid and return
- If element at mid is less than element being searched, lower =
mid+1, else upper = mid-1
3. ret=-1 (element not found)
Step 7: check()
1. If ret == -1, element was not found, printing appropriate message
2. Else element was found at index: ret, printing appropriate message
Step 8: Using linear search, calling linear_search() and then check()
Step 9: Using binary search, calling selection_sort() to sort array and then calling
binary_search() and check()
End

Implementation in Shell

#!/bin/bash
49

echo "Enter the Total numbers :"


read n
echo "Enter numbers:"
read -a a
echo "Enter number to be searched:"
read victim
linear_search () {
i=0
while [ $i -lt $n ]
do
if [ ${a[$i]} -eq $victim ]
then
ret=$i
return
fi
i=`expr $i + 1`
done
ret=-1
}

selection_sort () {
i=0
while [ $i -lt $n ]
do
j=`expr $i + 1`
while [ $j -lt $n ]
do
if [ ${a[$j]} -lt ${a[$i]} ]
then
temp=${a[$j]}
a[$j]=${a[$i]}
a[$i]=$temp
fi
j=`expr $j + 1`
done
i=`expr $i + 1`
done
}

binary_search () {
lower=0
upper=`expr $n - 1`
while [ $lower -le $upper ]
do
mid=`expr $upper + $lower`
mid=`expr $mid / 2`
if [ ${a[$mid]} -eq $victim ]
50

then
ret=$mid
return
fi
if [ ${a[$mid]} -lt $victim ]
then
lower=`expr $mid + 1`
else
upper=`expr $mid - 1`
fi
done
ret=-1
}

check () {
if [ $ret -eq -1 ]
then
echo "Item not found"
else
echo "Item found"
fi
}

echo "Using linear search"


linear_search
check
echo "Using binary search"
selection_sort
binary_search
check

Output Sets

➜ assignments ./ass18.sh
Enter the Total numbers :
5
Enter numbers:
6 7 4 5 2
Enter number to be searched:
1
Using linear search
Item not found
Using binary search
Item not found
➜ assignments ./ass18.sh
Enter the Total numbers :
10
Enter numbers:
51

8 4 0 2 8 5 3 6 11 65
Enter number to be searched:
5
Using linear search
Item found
Using binary search
Item found

You might also like