ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

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.