Home » Ruby programming

Ruby for loop with examples

for loop in Ruby: In this tutorial, we are going to learn about the for loop in Ruby programming with its syntax, examples.
Submitted by Hrithik Chandra Prasad, on July 31, 2019

The for loop

In programming, for loop is a kind of iteration statement which allows the block to be iterated repeatedly as long as the specified condition is not met or a specific number of times that the programmer knows beforehand. A for loop is made of two parts:

  1. The header part
  2. The actual body

The header part is used to specify the number of iterations. Most of the times it explicitly mentions the count of iterations with the help of a variable. for loop is generally used when the number of iterations is explicitly known before the execution of the statement declared within its block. The actual body contains the expressions or statements which will be implemented once per repetition.

It is a kind of Entry control loop. Generally, you can easily make an infinite loop through for loop by using the following syntax:

    for(;;)
    {
        #body
    }

In Ruby, for loop is implemented with the help of the following syntax:

    for variable_name[, variable...] in expression [do]
        # code to be executed
    end 

Example 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 		#implementation of for loop for 
	#pre-specified range 1..10
	k=i*num
	puts "#{num} * #{i}  = #{k}"
	i+=1		#incrementing the counter variable
end

Output

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

Example 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)    #lower limit can not be 
	#equal to or greater than upper limit 
	puts "Invalid lower limit"
else
	for i in num..100 #implementation of for loop for 
	#pre-specified range num..100
		if (i%2==0)
		puts "#{i} is even"
	else
		puts "#{i} is odd"
	end
	i=i+1 	#incrementing the counter variable
	end
end

Output

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

The for loop is one of the most commonly used loops in programming. As it is preferable and has easy syntax.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.