Tuesday, January 29, 2013

Nested While Loops...FINALLY!

So I am finally starting to get the hand of nested While loops. It was killing me and at first I was basically guessing my way to it with some hints, but in order to survive at DBC I need to have the core understanding of the fundamentals to build upon from day 1. Here is my print_triangle method. The first while loop is simply used for putsing a line to count up from. The nested while loop is where I am really focused on. What is happening when I run this method is the first while loop silently counts up by one while only putsing a space while the nested while loop (y) recognizes that x = 1, 2, 3, etc. and prints to count out until it reaches x. From there it is as simple as having it print "*" instead of the integer y itself and you have yourself a print_triangle with a nested while loop. My next step is going to be mastering recursion as I will have to have full understanding of this in order to really start grasping the fundamentals...to be continued


def print_triangle(n)
  x = 0
    while x < n
        x += 1
        y = 0
        while y < x
            y += 1
            print "*"
        end
      puts ''
    end
end

No comments:

Post a Comment