Iterative Code

We can understand the steps while considering the very simple problem of summing the array. Writing an iterative code would mean running a loop through the array adding each element to a variable and then returning the variable.

Example:

Ruby
# Iterative program to execute the 
# summing of a given array of numbers. 
def iterativeSum(arrayofNumbers)
  sum = 0
  arrayofNumbers.each do |number|
    sum += number
  end
  print sum
end

iterativeSum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Output
55

Recursion in Ruby

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. Recursion makes the process easier and it reduces a lot of compiling time. In Ruby, we can put all the actions in a loop, so that they can be repeated a number of times. So why is there a need for Recursion?

Since in Ruby, we introduce real-life variables, Recursion plays a vital role in solving major real-life problems in Ruby. 

Table of Content

  • Iterative Code
  • Recursive Code

Similar Reads

Iterative Code

We can understand the steps while considering the very simple problem of summing the array. Writing an iterative code would mean running a loop through the array adding each element to a variable and then returning the variable....

Recursive Code

In this code, the method calls itself. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems....