2

I have a list of numbers 1 2 3 4 5 that I am trying to organize into an array where the values are in a sequence where the current value is the summation of the previous values in the array (like this): 1 3 6 10 15. My current code is as follows:

array=()
for n in `seq 1 5`
do
    if [ $n -eq 1 ]; then
        array+=($n)
    else
        value=$n
        index="$(($n-1))"
        array+=(`echo ${array[$index]}+$value`)
    fi

done

However, when I try checking the array echo "${array[@]}" I get 1 +2 +3 +4 +5. How can I best go about solving this problem?

1
  • This doesn't answer your question but your code boils down to: for n in {1..5}; do ((array[n] = n * (n+1) / 2)); done Commented Oct 6, 2018 at 14:21

2 Answers 2

2

It is quite simple if you know how to get the last element of the array in bash arrays!. You can just use a negative index ${myarray[-1]} to get the last element. You can do the same thing for the second-last, and so on; in Bash:

fbseries=()

for ((i=1; i<=5; i++)); do
    if [ "$i" -eq 1 ]; then
        fbseries+=("$i")
    else
        fbseries+=( $(( ${fbseries[-1]} + $i )) )
    fi
done

With the example and some modifications all you need is as above.

Sign up to request clarification or add additional context in comments.

Comments

1

You are pretty close the a working code. Here I also added some improvements:

array=()
for n in {1..5}
do
    if [ "$n" -eq 1 ]; then
        array+=("$n")
    else
        value="$n"
        index="$((n-1))"
        array+=($((${array[$index]}+value)))
    fi
done

You can avoid using seq, and you don't need an echo but a calculus.

BTW, that's not a Fibonacci serie.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.