ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.