Wednesday, January 30, 2013

Nested While Loops: Lesson 2

It's all finally making sense. After having nested while loops baffle me I am finally starting to understand the basic principles that guide them. Lesson number two that kept me from solving this problem until now:

If you look at the y = 0 portion of this method, it HAS to be inside the x while loop. The reason for this is if it is outside and you run the y while loop it will stop after one turn because it will reach n. By putting the y = 0 INSIDE of the x while loop you are setting it to trigger as many times as the x while loop is continuing to operate with n = number of x while loops that puts ' '. The only reason why I printed the y*x and turned the integer into a string was so that I could +  '  ' space in between the numbers to style it a little better.


def times_table(n)
  x = 0
  while x < n
    x += 1
    y = 0
    while y < n
      y += 1
      print (y * x).to_s + ' '
    end
    puts ' '
  end
end

No comments:

Post a Comment