Home » Ruby programming

Ruby do...while loop with examples

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

The do while loop

In programming, do...while loop works in the same way as a while loop with a basic difference that the specified Boolean condition is evaluated at the end of the block execution. This result in the execution of statements at least for once and later iterations depend upon the result of the Boolean expression. A process symbol and a Boolean condition is used to make a do...while iteration.

In this loop, at first, the block defined inside the code is executed then the given condition is checked. Due to this property, it is also known as post-test loop.

A do...while loop is an example of the exit-control loop because in this the code is executed before the evaluation of the specified condition. It runs till the Boolean condition stands to be true, once it evaluates to be false the loop gets terminated at that point of time.

In Ruby, the do...while loop is implemented with the help of the following syntax:

    loop do
        # code block to be executed
        break if Boolean_Expression #use of break statement
    end

Example 1:

=begin 
Ruby program to check whether the given 
number is Armstrong or not using a do-while loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
sum = 0

loop do
	#implementation of the do-while loop
	rem=num%10
	num=num/10
	sum=sum+rem*rem*rem
	puts "Checking......"
	if num==0
		break
	end
end

if(temp==sum)
	puts "The #{temp} is Armstrong"
else
	puts "The #{temp} is not Armstrong"
end

Output

First run:
Enter the number
135
Checking......
Checking......
Checking......
The 135 is not Armstrong

Second run:
Enter the number
1
Checking......
The 1 is Armstrong

Example 2:

=begin 
Ruby program to check wether the given number 
is having five or not using do-while loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
sum = 0
flag=false #flag is a Boolean variable

loop do
	#implementation of the do-while loop
	rem=num%10
	num=num/10
	if(rem==5)
		flag=true #flag is made true if the presence is found
	end
	puts "Checking......"
	if num==0
		break
	end
end

if(flag==true)
	puts "We have found the presence of five in #{temp}"
else
	puts "We have not found the presence of five in #{temp}"
end

Output

First run:
Enter the number
1234566
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
We have found the presence of five in 1234566

Second run:
Enter the number
198762
Checking......
Checking......
Checking......
Checking......
Checking......
Checking......
We have not found the presence of five in 198762


Comments and Discussions!

Load comments ↻





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