Chapter 6: Iteration

6.1 Multiple assignment

#!/usr/bin/env ruby

fred = 5
puts 5
fred = 7
puts 7

########################################

a = 5
b = a # a and b are now equal
a = 3 # a and b are no longer equal

6.2 Iteration

6.3 The while statement

#!/usr/bin/env ruby

def countdown(n)
  while n > 0
    puts n
    n = n - 1
  end
  puts "Blastoff!"
end

countdown(5)

########################################

def sequence(n)
  while n != 1
    puts n
    if n % 2 == 0 # n is even
      n = n / 2
    else          # n is odd
      n = n*3 + 1
    end
  end
end

sequence(9)
#sequence(0) # infinite loop for n < 1 !

6.4 Tables

#!/usr/bin/env ruby

x = 1.0
while x < 10
  puts x.to_s + "   " + Math.log(x).to_s
  x = x + 1
end

########################################

x = 1.0
while x < 10
  puts x.to_s + "   " + (Math.log(x) / Math.log(2)).to_s
  x = x + 1
end

########################################

x = 1.0
while x < 100
  puts x.to_s + "   " + (Math.log(x) / Math.log(2)).to_s
  x = x * 2
end

6.5 Two-dimensional tables

#!/usr/bin/env ruby

i = 1
while i <= 6
  print 2 * i
  print "   "
  i = i + 1
end
puts

6.6 Encapsulation and generalization

#!/usr/bin/env ruby

def print_multiples(n)
  i = 1
  while i <= 6
    print n * i
    print "   "
    i = i + 1
  end
  puts
end

#print_multiples(3)
#print_multiples(4)

########################################

i = 1
while i <= 6
  print_multiples(i)
  i = i + 1
end

6.7 Methods

6.8 More encapsulation

#!/usr/bin/env ruby

# from earlier
def print_multiples(n)
  i = 1
  while i <= 6
    print n * i
    print "   "
    i = i + 1
  end
  puts
end

def print_mult_table
  i = 1
  while i <= 6
    print_multiples(i)
    i = i + 1
  end
end

print_mult_table

6.9 Local variables

6.10 More generalization

#!/usr/bin/env ruby

def print_multiples(n, high)
  i = 1
  while i <= high
    print n * i
    print "   "
    i = i + 1
  end
  puts
end

def print_mult_table(high)
  i = 1
  while i <= high
    print_multiples(i, high)
    i = i + 1
  end
end

print_mult_table(7)

########################################

def print_mult_table(high)
  i = 1
  while i <= high
    print_multiples(i, i)
    i = i + 1
  end
end

print_mult_table(7)

6.11 Glossary

6.12 Exercises

GNU Free Documentation License Valid HTML Valid CSS Built with BBEdit
Friendly links for Google “juice”