Search code examples
rubywhile-loopnested-loops

Creating a triangle out of numbers with nested while loops


The teacher for my Ruby class has a program that asks the user for a number and then counts up or down from the number into a triangle shape. If the user enters the number 5, it prints:

12345
1234
123
12
1

This is the teacher's code:

print "Enter a starting number: "
size = gets.to_i
line = 0
while line < size
  count = 1
  while count <= size - line
    print count
    count += 1
  end
  puts
  line += 1
end

For the class, I need to do the same thing as above along the lines of my teacher's code, but start from 1 and count up to the number that the user entered. For example, if the user enters 5, I need to print:

1
12
123
1234
12345

I'm not looking for someone to do my assignment for me, I just need some help and I'm hoping someone can guide me in the right direction.


Solution

  • If you have to use while loops based on your example, try:

    print "Enter a starting number: "
    size = gets.to_i
    line = 1
    
    while line <= size
        count = 1
        while count <= line
            print count
            count += 1
        end
        puts
        line += 1
    end
    

    Else try:

    print "Enter n: "
    n = gets.to_i
    puts
    
    (1..n).each do |i|
        (1..i).each {|j| print j }
        puts
    end