954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursive way?

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

trume
Newbie Poster
19 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 
danuz
Newbie Poster
12 posts since Dec 2010
Reputation Points: 10
Solved Threads: 1
 

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

trume
Newbie Poster
19 posts since Feb 2011
Reputation Points: 10
Solved Threads: 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.

shibblez
Junior Poster in Training
72 posts since Oct 2010
Reputation Points: 15
Solved Threads: 6
 

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

trume
Newbie Poster
19 posts since Feb 2011
Reputation Points: 10
Solved Threads: 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.

griswolf
Veteran Poster
1,165 posts since Apr 2010
Reputation Points: 344
Solved Threads: 256
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You