0% found this document useful (0 votes)
13 views12 pages

Week 12 Usp Lab Programs

USP Lab

Uploaded by

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

Week 12 Usp Lab Programs

USP Lab

Uploaded by

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

USP LAB Week 12

Task 1: Reverse Numbers


AIM

To write a shell script that takes a number as input from the user and displays the reverse of
the given number.

Description

This shell script reads a number from the user and reverses its digits using mathematical
operations.

 Modulus operation (%) is used to extract the last digit.


 Multiplication and addition are used to build the reversed number step-by-step.
 Division (/) helps remove the last digit from the original number after each iteration.
 A while loop runs the logic repeatedly until the input number becomes 0.

Key Concepts Used in the Code

1. Looping Structure:
o A while loop ensures the reversal logic runs until all digits are processed (i.e.,
the input number becomes 0).
2. Arithmetic Operations:
o Modulus (%): Extracts the last digit of the number.
o Multiplication and Addition: Used to build the reversed number.
o Division (/): Removes the last digit from the original number after every
iteration.
3. Conditional Execution:
o The loop continues only if the input number is greater than 0 ([ $number -
gt 0 ]).

Code
#!/bin/ksh

# Prompt the user to enter a number


echo "Enter a number:"
read number

# Initialize the reverse variable


reverse=0

# Loop until the number becomes 0


while [ $number -gt 0 ]
do
# Extract the last digit using modulus operation
remainder=$(( $number % 10 ))

# Build the reversed number


reverse=$(( $reverse * 10 + $remainder ))

# Remove the last digit from the original number


number=$(( $number / 10 ))
done

# Display the reversed number


echo "Reversed Number is: $reverse"

Explanation of the Code

1. Reading Input:
o The user is prompted to enter a number, which is stored in the variable
number.
2. Initializing Variables:
o The reverse variable is initialized to 0 to store the reversed number.
3. Using a While Loop:
o The while loop runs until the input number becomes 0.
o In each iteration:
 The remainder is extracted using the modulus operation (number %
10).
 The reversed number is built by multiplying the current reverse by 10
and adding the remainder.
 The last digit is removed from the original number using division
(number / 10).
4. Displaying Output:
o Once the loop completes, the reversed number is printed to the screen.

Output Examples

Example Run 1

$ ./12_1_reverseanumber.ksh
Enter a number:
234
Reversed Number is: 432

Example Run 2

$ ./12_1_reverseanumber.ksh
Enter a number:
4219
Reversed Number is: 9124

Inferences

 This script effectively demonstrates looping and arithmetic operations in shell


scripting.
 It efficiently reverses the digits of a number using the while loop and modulus
operations.
 Shell scripts are powerful tools for implementing such mathematical logic with ease.
Task 2: File Handling Menu
AIM

To write an interactive shell program that offers the user multiple options to copy, remove,
rename, or link files.

Description

This script provides a menu-based interface for performing basic file handling operations.
The operations include:

1. Copying a file
2. Removing a file
3. Renaming a file
4. Creating a symbolic link
5. Exiting the menu

The user selects an option from the menu, and the corresponding file operation is executed
using the appropriate shell commands like cp, rm, mv, and ln -s. The script keeps running
until the user chooses to exit by selecting Option 5.

Code
#!/bin/ksh

# Infinite loop to keep displaying the menu until the user chooses to exit
while true; do
# Display the menu options
echo "File Handling Menu"
echo "1. Copy File"
echo "2. Remove File"
echo "3. Rename File"
echo "4. Create Symbolic Link"
echo "5. Exit"
echo "Enter your choice: "

# Read the user's choice


read choice

# Perform the operation based on the user's choice using a case


statement
case $choice in
1) # Copy File
echo "Enter the source file name:"
read src
echo "Enter the destination file name:"
read dest
cp $src $dest
echo "File copied successfully."
;;
2) # Remove File
echo "Enter the file name to remove:"
read file
rm $file
echo "File removed successfully."
;;
3) # Rename File
echo "Enter the current file name:"
read oldname
echo "Enter the new file name:"
read newname
mv $oldname $newname
echo "File renamed successfully."
;;
4) # Create Symbolic Link
echo "Enter the target file name:"
read target
echo "Enter the link name:"
read linkname
ln -s $target $linkname
echo "Symbolic link created successfully."
;;
5) # Exit the script
break
;;
*) # Invalid choice handling
echo "Invalid choice, please try again."
;;
esac
done

Explanation of the Code

1. Menu Display and Input Handling:


o The while true loop ensures the menu keeps appearing until the user
chooses to exit.
o The user is prompted to enter their choice, which is stored in the choice
variable.
2. Switch-Case Statement:
o The case statement processes the user’s input and performs the
corresponding file operation:
 Option 1: Copy a file using cp command.
 Option 2: Remove a file using rm command.
 Option 3: Rename a file using mv command.
 Option 4: Create a symbolic link using ln -s command.
 Option 5: Exit the menu by using break.
3. Invalid Input Handling:
o If the user enters an invalid option, the script displays an error message:
"Invalid choice, please try again."
4. Shell Commands Used:
o cp: Copies a file from one location to another.
o rm: Deletes a specified file.
o mv: Renames or moves a file.
o ln -s: Creates a symbolic link to a target file.
Output Examples

Example Run 1

$ ./12_2_switch_case.ksh
File Handling Menu
1. Copy File
2. Remove File
3. Rename File
4. Create Symbolic Link
5. Exit
Enter your choice:
1
Enter the source file name:
a.txt
Enter the destination file name:
b.txt
File copied successfully.

Example Run 2

File Handling Menu


1. Copy File
2. Remove File
3. Rename File
4. Create Symbolic Link
5. Exit
Enter your choice:
2
Enter the file name to remove:
b.txt
File removed successfully.

Example Run 3

File Handling Menu


1. Copy File
2. Remove File
3. Rename File
4. Create Symbolic Link
5. Exit
Enter your choice:
3
Enter the current file name:
a.txt
Enter the new file name:
b.txt
File renamed successfully.

Example Run 4

File Handling Menu


1. Copy File
2. Remove File
3. Rename File
4. Create Symbolic Link
5. Exit
Enter your choice:
4
Enter the target file name:
b.txt
Enter the link name:
x.txt
Symbolic link created successfully.

Example Run 5

File Handling Menu


1. Copy File
2. Remove File
3. Rename File
4. Create Symbolic Link
5. Exit
Enter your choice:
5
$

Inferences

This interactive script offers a simple and effective way to manage files through a menu-
driven interface. It demonstrates the usage of basic file handling commands in KornShell
scripting (KSH) and ensures that each operation is executed based on the user’s input. The
script also showcases control flow using case statements and infinite loops.

Task 3: Fibonacci Series


AIM

To write a shell script that displays the Fibonacci series up to a given number of terms.

Description

The Fibonacci series is a sequence of numbers where each term is the sum of the two
preceding ones, starting from 0 and 1.

 The first few terms of the Fibonacci series are:


0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The script takes the number of terms as input from the user and displays the corresponding
Fibonacci sequence using a for loop.

#!/bin/ksh

# Prompt the user to enter the number of terms


echo "Enter the number of terms for the Fibonacci series:"
read terms # Read the input number of terms
# Initialize the first two terms of the series
a=0
b=1

echo "Fibonacci Series:"

# Loop to generate the Fibonacci series


for (( i=0; i<terms; i++ ))
do
echo "$a" # Print the current term
fn=$((a + b)) # Calculate the next term
a=$b # Shift 'a' to the value of 'b'
b=$fn # Shift 'b' to the new calculated term
done

Explanation of the Code

1. Input Handling:
o The user is prompted to enter the number of terms to generate using:

echo "Enter the number of terms for the Fibonacci


series:"
read terms

2. Variable Initialization:
o a and b are initialized to 0 and 1, which are the first two terms of the
Fibonacci series.
3. Using the for Loop:
o The for loop runs from 0 to the entered number of terms (terms - 1).
Example: If the user enters 10, the loop runs 10 times.
o At each iteration:
1. The current value of a is printed.
2. fn stores the sum of a and b (the next Fibonacci term).
3. a is updated to the value of b.
4. b is updated to the value of fn.
4. Output Display:
o After the loop ends, the complete Fibonacci series is displayed on the
terminal.

Output Examples

Example 1

$ ./12_3_fibonacci.ksh
Enter the number of terms for the Fibonacci series:
10
Fibonacci Series:
0
1
1
2
3
5
8
13
21
34

Example 2

$ ./12_3_fibonacci.ksh
Enter the number of terms for the Fibonacci series:
5
Fibonacci Series:
0
1
1
2
3

Key Concepts

1. Fibonacci Series Logic:


o Each term is generated by adding the previous two terms:
 Example: 2 = 1 + 1, 3 = 2 + 1, 5 = 3 + 2, and so on.
2. Looping with for:
o The for loop ensures that the series is generated for the number of terms
requested by the user.
3. Shifting Variables:
o The values of a and b are updated in each iteration to track the next terms in
the sequence.

Inferences:

This shell script provides a practical demonstration of generating the Fibonacci series
using simple arithmetic operations and loop constructs in KornShell scripting.

Task 4: Palindrome Checking


AIM

To write a shell script that checks whether the given string is a palindrome.

Description

A palindrome is a string that reads the same backward as forward (e.g., "madam", "level").
The script takes a string as a command-line argument and determines if the input string is a
palindrome by reversing it and comparing it with the original. If both are identical, the script
prints that the string is a palindrome; otherwise, it prints that the string is not a palindrome.

Code

#!/bin/ksh

# Check if an argument is provided


if [ -z "$1" ]; then
echo "Usage: $0 <string>"
exit 1
fi

input=$1 # Store the input string from the command-line argument


reverse=$(echo $input | rev) # Reverse the input string using 'rev' command
# Check if the original string is equal to the reversed string
if [ "$input" = "$reverse" ]; then
echo "$input is a palindrome."
else
echo "$input is not a palindrome."
fi

Explanation of the Code

1. Checking for Input


o The script verifies if a command-line argument is provided using:

if [ -z "$1" ]; then

o -z checks if the string is empty. If no argument is provided, the script displays


usage instructions and exits with status 1:

echo "Usage: $0 <string>"


exit 1

2. Storing Input and Reversing the String


o The input string is assigned to the variable input:

input=$1

o The rev command is used to reverse the input string and store it in reverse:

reverse=$(echo $input | rev)

3. Comparing the Original and Reversed Strings


o The if statement compares the original string with the reversed string:

if [ "$input" = "$reverse" ]; then


o If both are identical, the string is a palindrome:

echo "$input is a palindrome."

o Otherwise, the string is not a palindrome:

echo "$input is not a palindrome."

Output Examples

Example 1: No Input Provided

$ ./12_4_palindrome.ksh
Usage: ./12_4_palindrome.ksh <string>

Example 2: Palindrome Input

$ ./12_4_palindrome.ksh madam
madam is a palindrome.

Example 3: Non-palindrome Input

$ ./12_4_palindrome.ksh mvgr
mvgr is not a palindrome.

Explanation of Key Concepts

1. Command-line Arguments:
o The first argument provided to the script is accessed using $1.
2. Using rev Command:
o The rev command reverses the input string.
Example: echo madam | rev outputs madam.
3. String Comparison:
o The = operator is used inside the if statement to check if the original and
reversed strings are identical.
4. Exit Status:
o exit 1 is used to exit the script if no input is provided, indicating an error.

Inferences:

This script demonstrates how to use command-line arguments, string reversal, and
conditional checks in KornShell scripting. It helps students understand basic string
manipulation and comparison logic in a shell environment.

Task 5: Factorial of a given Number


AIM
To write a shell script that calculates the factorial of a given number.
Description
The factorial of a number is the product of all positive integers from 1 to that number. It is
denoted as n! and calculated as:
n! = n × (n - 1) × (n - 2) × ... × 1
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The script takes a number as input and calculates
its factorial using a for loop.
Code

#!/bin/ksh
echo "Enter a number:" # Prompt user to enter a number
read number # Read the input from the user
factorial=1 # Initialize factorial to 1
# Loop from 1 to the input number
for (( i=1; i<=number; i++ ))
do
factorial=$((factorial * i)) # Multiply factorial with the current value of i
done

# Display the result


echo "Factorial of $number is $factorial."

Explanation of the Code


1. Input Handling
o The user is prompted to enter a number using the echo command.
o The input is read and stored in the number variable using:
read number
2. Initialization
o The variable factorial is initialized to 1 to store the product of numbers.
3. Using the for Loop
o The for loop iterates from 1 to the value of the input number:
for (( i=1; i<=number; i++ ))
 At each iteration, the current value of i is multiplied with the existing
value of factorial. Example:
If i = 3 and factorial = 2 from the previous iteration, then:
factorial = 2 * 3 = 6
4. Displaying the Result
o After the loop ends, the factorial of the input number is printed using:
echo "Factorial of $number is $factorial."

Output Examples
Example 1
$ ./12_5_factorial.ksh
Enter a number:
10
Factorial of 10 is 3628800.
Example 2
$ ./12_5_factorial.ksh
Enter a number:
5
Factorial of 5 is 120.
Explanation of Key Concepts
1. Looping with for:
o The for loop helps in repeatedly multiplying numbers from 1 to the input
number.
2. Arithmetic Operations:
o The * operator performs multiplication.
o (( ... )) is used for arithmetic expansion within the loop.
3. Handling Edge Cases:
o If the input number is 0, the script still works correctly since 0! = 1.
Inferences:
This shell script demonstrates how to calculate the factorial of a number using a for loop in
KornShell scripting. It provides hands-on experience with loops, arithmetic operations,
and basic input handling.

You might also like