Home »
Ruby programming
Ruby nested while loop with examples
Nested while loop in Ruby: In this tutorial, we are going to learn about the nested while loop in Ruby programming language with syntax and examples.
Submitted by Hrithik Chandra Prasad, on August 01, 2019
Nested while loop
When one while loop is living inside another while loop, it is known as nesting of while loop. It means that there are two while loops, the first one is acting as an outer loop and later one is behaving as the inner loop. Execution will take place in the manner that first the outer ‘while’ loop is triggered, then if the specified Boolean condition is matched the pointer will be passed to inner ‘while’ loop. In this too, if the Boolean condition stands to be true, the inner while loop body will be executed until specified condition does not come out to be false. Once the inner loop completes its execution, the pointer will be passed back to the outer for loop for its successful execution.
In Ruby, Nesting of the while loop can be done with the help of the following syntax:
while (condition )
while (condition )
# code to be executed
end
#expressions
end
Example 1:
We can print various patterns using nested while loops. Let us see how the following pattern can be printed.
1
22
333
4444
55555
Code:
=begin
Ruby program to print a pattern using nested while loop
=end
num=0
while (num!=6)
j=0
while(j!=num)
print num
j+=1
end
puts ""
num+=1
end
Example 2:
=begin
Ruby program to check number of palindrome numbers present
between two limits using nested while loop
=end
puts "Enter upper limit:-"
ul=gets.chomp.to_i
puts "Enter lower limit:-"
ll=gets.chomp.to_i
while(ul!=ll)
num=ul
temp=ul
pal=0
while(num!=0)
rem=num%10
num=num/10
pal=pal*10+rem
end
if temp==pal
puts "#{temp} is palindrome"
end
ul=ul-1
end
Output
Enter upper limit:-
200
Enter lower limit:-
10
191 is palindrome
181 is palindrome
171 is palindrome
161 is palindrome
151 is palindrome
141 is palindrome
131 is palindrome
121 is palindrome
111 is palindrome
101 is palindrome
99 is palindrome
88 is palindrome
77 is palindrome
66 is palindrome
55 is palindrome
44 is palindrome
33 is palindrome
22 is palindrome
11 is palindrome
You can observe in the above program that first the outer while loop is checked through a specified condition i.e. while loop will run until upper limit does not become equal to the lower limit.
The upper limit is passed as the number for which Palindrome check will be carried out using an inner while loop. The inner while loop has all those statements which are necessary to carry out the checking. Once, the inner evaluation is done. The pointer is going back to the outer loop and the upper limit is getting decreased by 1.