Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to print Floyd's triangle in Ruby

1 Answer

0 votes
# Floyd's Triangle in Ruby
#
# Floyd's Triangle is a simple numeric pattern:
#   Row 1: 1
#   Row 2: 2 3
#   Row 3: 4 5 6
#   Row 4: 7 8 9 10
#
# This program:
#   • Uses a helper method to generate the next number.
#   • Uses Ruby's built‑in iteration methods.
#   • Uses clean, idiomatic Ruby style.
#   • Includes detailed comments explaining each part.

# Helper method:
# Receives the current counter (Integer) and returns the next number.
# Using a method keeps the main loop clean and readable.
def next_number(counter)
  counter + 1
end

# Prints Floyd's Triangle with the given number of rows.
# Uses Ruby's times and each loops for clarity and idiomatic style.
def print_floyd_triangle(rows)
  counter = 0  # Start before 1 so the first generated number is 1

  1.upto(rows) do |row|
    row.times do
      counter = next_number(counter)
      print "#{counter} "
    end
    puts  # End of row
  end
end

# Main program:
# Reads number of rows from the user and prints Floyd's Triangle.
n = 7

if n < 1
  puts "Number of rows must be positive."
  exit
end

puts "Floyd's Triangle with #{n} rows:"
print_floyd_triangle(n)


=begin
run:

Floyd's Triangle with 7 rows:
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 

=end

 



answered Jul 10 by avibootz
...