B.Sc Computer Science with Data analytics
Linux and Shell Programming - Lab
Bharathiar University
Program 7- Write a Shell script to print the first n Fibonacci numbers
Source Code
# Function to print the first n Fibonacci numbers
print_fibonacci() {
# Initialize variables for the first two Fibonacci numbers
num1=0
num2=1
count=0
# Print the first two Fibonacci numbers
echo "The first $n Fibonacci numbers are:"
echo "$num1"
echo "$num2"
# Calculate and print the remaining Fibonacci numbers
while [ $count -lt $(($n - 2)) ]; do
next=$((num1 + num2))
echo "$next"
num1=$num2
num2=$next
count=$((count + 1))
done
}
# Main program starts here
# Prompt the user to enter the number
echo "Enter the a number of fibonacci series to print: "
read n
# Check if n is a positive integer
if [[ "$n" -lt 1 ]]; then
echo "Error: Please provide a positive integer."
exit 1
fi
# Print the first n Fibonacci numbers
print_fibonacci $n
No comments:
Post a Comment