Ruby program to print numbers from 1 to 5 using for loop, while, and do...while loop

Ruby Looping Example: Write a program to print numbers from 1 to 5 using for loop, while, and do...while loop.
Submitted by Nidhi, on December 19, 2021

Problem Solution:

In this program, we will print numbers from 1 to 5 using for loop, while, and do while loop. Here, we use a counter variable to iterate numbers.

Program/Source Code:

The source code to print numbers from 1 to 5 using for loop, while, and do while loop is given below. The given program is compiled and executed successfully.

# Ruby program to print numbers from 1 to 5 
# using the for loop, while, and do loop

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

puts "\nWhile Loop:";
cnt=1;
while cnt<=5
  print cnt," "; 
  cnt = cnt + 1;
end   

puts "\nDo While Loop:";
cnt=1;
loop do
    print cnt," "; 
    if cnt==5
        break;
    end
    cnt = cnt + 1;
end

Output:

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

Explanation:

In the above program, we used while, do, and for loop to print numbers from 1 to 5.

Ruby Looping Programs »




Comments and Discussions!

Load comments ↻





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