×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

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

Last Updated : December 15, 2025

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 »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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