This simple program help you to logically put and modify the vars as per the requirement, helping you to understand the fibonacci series
#!/bin/bash
# First Number of the Fibonacci Series
a=0
# Second Number of the Fibonacci Series
b=1
# Number of terms to generate (provided as a command-line argument)
N=$1
# Check if input is valid
if [[ -z "$N" || "$N" -le 0 ]]; then
echo "Please provide a positive integer as input."
exit 1
fi
# Initialize the sum variable
sum=0
echo "The Fibonacci series is:"
for ((i = 0; i < N; i++)); do
echo -n "$a "
# Add the current term to the sum
sum=$((sum + a))
# Calculate the next Fibonacci number
fn=$((a + b))
a=$b
b=$fn
done
echo
echo "The sum of the Fibonacci series is: $sum"
O/P
Flow:
Initialization
- The script begins by initializing the first two terms of the Fibonacci series:
- a=0: The first term.
- b=1: The second term.
- The user provides the number of terms (N) as a command-line argument ($1).
Loop Through N Terms
- A for loop runs from 0 to N-1 (inclusive):
- Print the Current Term: The value of a is printed, representing the current Fibonacci term.
- Calculate the Next Term:
- Compute the next term: fn = a + b.
- Update a to hold the value of b (shift one position forward).
- Update b to hold the value of fn (next term).
- The loop ensures all terms are generated iteratively without recursion.
Calculate the Sum
- During the loop, each term (a) is added to the variable sum to keep track of the total.
- Once the loop finishes, the sum of all Fibonacci numbers is displayed