Ruby program to demonstrate the 'break' statement with 'while', 'until', and 'for' loops

Ruby Example: Write a program to demonstrate the 'break' statement with 'while', 'until', and 'for' loops.
Submitted by Nidhi, on December 20, 2021

Problem Solution:

In this program, we will use the "break" statement with "while", "until", and "for" loops to terminate the loop when the given if statement is true.

Program/Source Code:

The source code to demonstrate the "break" statement with "while", "until", and "for" loops is given below. The given program is compiled and executed successfully.

# Ruby program to demonstrate the "break" statement 
# with "while", "until", and "for" loops

puts "While Loop:";
cnt=1;
while cnt<=10
    print cnt," ";
    if cnt==5
        break;
    end
    cnt=cnt+1;
end
puts;
    
puts "Until Loop:";
cnt=1;
until cnt==11
    print cnt," ";
    if cnt==5
        break;
    end
    cnt=cnt+1;
end
puts;

puts "For Loop:";    
for cnt in 1..11 do   
    print cnt," ";
    if cnt==5
        break;
    end
end

Output:

While Loop:
1 2 3 4 5 
Until Loop:
1 2 3 4 5 
For Loop:
1 2 3 4 5

Explanation:

In the above program, we used the break statement with "while", "until", and "for" loop to terminate the loop when the value of the cnt variable is equal to 5.

Ruby Looping Programs »




Comments and Discussions!

Load comments ↻





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