0

Hello,

How can I do it on a recursive way? (Function ''plus'' needs to call itself)

#!/bin/bash
function plus
{
	let GLOBAL=$GLOBAL+$1
}
GLOBAL=0
n=$1
for ((i=1; i<=n; i++))
do
plus $i
done
echo Answer: $GLOBAL

Any help is welcome!

Regards,
trume

Edited by trume: /

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by griswolf
0

Yes, but your code wasn't have correct function. It needs to be as most similar to mine ( SUM ).

0

Put

set -xv

as your second line. You can now see what is happening as it executes. A clue -

plus $i

doesn't do what you think it does.

0

Actaully, I need suggestions about the recursion. How to make function will call itself...

0

There are many shells. Which one are you using?
The normal meaning for PLUS parameters is" Return the sum of all the parameters", so the recursive way would be to

  • return PLUS (first+second) rest of the parameters
  • Or calculate (i, i+1) for i in the proper range and return PLUS pair-sums

Or something that does part of the work now and defers some of the work to a call of itself.

Edited by griswolf: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.