Howdypaudy
Howdypaudy

Reputation: 3

How to generate and sum up a sequence

Basically, what I'm trying to understand is that how to reassign a variable that was already declared before to a new value.

I want to reassign the variable to a different value in the loop. Then print that sum.

For example in JavaScript,

sum = 0;

for... (loop)
sum = sum + start-point; (loop body)

console.log(sum)

Now I don't seem to be able to get that in bash.

This is my code in bash

echo Enter a number:
read NUMBER
echo Enter a startpoint:
read STARTPOINT
echo Enter how many terms:
read TERMS
sum=0;
for ((n=0;n<$TERMS;n++));
do
   STARTPOINT=$((STARTPOINT + NUMBER))
   sum=$(($sum + $STARTPOINT))
        echo $STARTPOINT
        echo $sum
done

All the code is correct except the sum part, and because of it the code doesn't run properly. if I remove that part, it works fine. I just need to sum the outputs of the variable STARTPOINT.

Example

Input

NUMBER = 3 (means to increment 3 in the startpoint)
STARTPOINT = 2
TERMS = 5 (means to add 3 to 2 five times)

Expected output

5
8
11
14
17

And the part that I am having difficulty with is how to add all these numbers, when all added, it should print 55.

Upvotes: 0

Views: 141

Answers (1)

Socowi
Socowi

Reputation: 27225

In this answer I changed your variable names to be lowercase. This is the conventional naming scheme in bash to avoid accidental name collisions with built-in variables and environment variables.

If I understood correctly, you want to build the following sequence and also sum it up:

startpoint + 1*number + startpoint + 2*number + ... + startpoint+ term*number

In that case you should not change startpoint inside your loop. Use another variable to store the result of startpoint + n*number.

startpoint=2 number=3 terms=5 sum=0
echo "$terms times increment $startpoint by $number:"
for ((n=1; n<=terms; n++));
do
  ((addend = startpoint + n*number))
  echo "$addend"
  ((sum += addend))
done
echo "The sum is $sum"

However, instead of using a slow loop you could printing the sequence using seq and then calculate its sum using the closed formula for triangular numbers:

startpoint=2 number=3 terms=5
seq $((startpoint+number)) $number $((startpoint+terms*number))
((sum = terms*startpoint + terms*(terms+1)/2 * number))
echo "The sum is $sum"

Upvotes: 2

Related Questions