在编程中,for循环是一种迭代语句,只要不满足指定条件或程序员事先知道的特定次数,就可以重复迭代该块。一个for循环是由两个部分组成:
标头部分
实际的身体
标头部分用于指定迭代次数。在大多数情况下,它借助变量来明确提及迭代次数。当在其块内声明的语句执行之前明确知道迭代次数时,通常使用for循环。实际主体包含将重复执行一次的表达式或语句。
这是一种Entry控制循环。通常,您可以使用以下语法轻松地通过for循环进行无限循环:
for(;;) { #body }
在Ruby中,借助以下语法实现for循环:
for variable_name[, variable...] in expression [do] # 要执行的代码 end
范例1:
=begin Ruby program to print the table of the number specified by the user using for loop =end puts "Enter a number" num=gets.chomp.to_i for i in 1..10 #for循环的实现 #预定范围1..10 k=i*num puts "#{num} * #{i} = #{k}" i+=1 #增加计数器变量 end
输出结果
Enter a number 89 89 * 1 = 89 89 * 2 = 178 89 * 3 = 267 89 * 4 = 356 89 * 5 = 445 89 * 6 = 534 89 * 7 = 623 89 * 8 = 712 89 * 9 = 801 89 * 10 = 890
范例2:
=begin Ruby program to print the list of the odd and even numbers where the lower limit is specified by the user and the upper limit is 100 using for loop =end puts "Enter the lower limit(ul is 100)" num=gets.chomp.to_i if (num>=100) #下限不能 #等于或大于上限 puts "Invalid lower limit" else for i in num..100 #for循环的实现 #预定范围num..100 if (i%2==0) puts "#{i} is even" else puts "#{i} is odd" end i=i+1 #增加计数器变量 end end
输出结果
First run: Enter the lower limit 76 76 is even 77 is odd 78 is even 79 is odd 80 is even 81 is odd 82 is even 83 is odd 84 is even 85 is odd 86 is even 87 is odd 88 is even 89 is odd 90 is even 91 is odd 92 is even 93 is odd 94 is even 95 is odd 96 is even 97 is odd 98 is even 99 is odd 100 is even Second run: Enter the lower limit 900 Invalid lower limit
在for循环是编程中最常用的循环之一。最好是它并且语法简单。