Q:

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

belongs to collection: Ruby Looping Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby program to implement an infinite loop using t... >>