Testing express

Testing express

Monday, June 25, 2012

Recursion - A simple example in ruby

class Recursion 
   def sum_positive(n)
 
     if  n==1
        $t = 1
    else
        $t1= n.to_i + sum_positive(n-1)
    end


   end

end

s = Recursion.new
puts s.sum_positive(9)


Problem: Write a recursive Ruby function sum_positive(n) that has one parameter n that represents a positive integer. The function should return the sum of the first n positive integers. Your solution must use recursion and should not have a loop in it.
Eg;
sum_positive(5) must give

5+4+3+2+1 = 15 as output

Do you have a better solution?

No comments:

Post a Comment