Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Loop: to be dynamic?

Ok i'm actually doing this exercise to tackle those nested loop questions. I would say this would be the hardest one for me. I tried my best to be more dynamic instead of static. Can anyone give me tips on how to solve this?

expected output:

1
1 2
1 2 4
1 2 4 8
1 2 4 8 16
1 2 4 8 16 32
1 2 4 8 16 32 64
1 2 4 8 16 32 64 128

this is my static code:

n = 1
for i in 1..8

       for c in 1..n
               case i
                     when 1
                        print "1"
                     when 2
                        print "1 2"
                     when 3
                        print "1 2 4"
                     when 4
                        print "1 2 4 8"
                     when 5
                        print "1 2 4 8 16"
                     when 6
                        print "1 2 4 8 16 32"
                     when 7
                        print "1 2 4 8 16 32 64"
                     when 8
                        print "1 2 4 8 16 32 64 128"
               end
                  print "\n"
       end
end

I'm not looking for answer. But i would appreciate that you can guide me.

like image 324
Suresh Avatar asked Mar 13 '26 14:03

Suresh


1 Answers

for x in 0..7
  for y in 0..x
    op = 2**y
    print op, " "
  end
  puts ""
end

Prints

1 
1 2 
1 2 4 
1 2 4 8 
1 2 4 8 16 
1 2 4 8 16 32 
1 2 4 8 16 32 64 
1 2 4 8 16 32 64 128 
like image 93
Karan Shah Avatar answered Mar 16 '26 04:03

Karan Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!