Home »
Ruby »
Ruby Programs
Ruby program to demonstrate the 'break' statement with a nested loop
Ruby Example: Write a program to demonstrate the "break" statement with a nested loop.
Submitted by Nidhi, on December 20, 2021
Problem Solution:
In this program, we will use the "break" statement with nested "while" loop. If we use the break statement inside the inner loop then it terminates the only inner loop.
Program/Source Code:
The source code to demonstrate the "break" statement with the nested loop is given below. The given program is compiled and executed successfully.
# Ruby program to demonstrate the
# "break" statement with nested loop
cnt1=1;
cnt2=0;
while cnt1<=5
cnt2=1;
while cnt2<=10
print cnt1, " ";
if(cnt2 == 5)
break;
end
cnt2 = cnt2 + 1;
end
cnt1=cnt1+1;
puts;
end
Output:
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
Explanation:
In the above program, we used the "break" statement inside the inner loop. In the case of a nested loop, if we use the break statement nested loop inside the inner loop then it terminates the inner loop.
In our program, the normally inner loop executes 10 times but it will execute only 5 times because of the break statement.
Ruby Looping Programs »