This set of Ruby Programming Multiple Choice Questions & Answers (MCQs) focuses on “While Loop”.
1. While loop checks the condition and the loop keeps on running till the condition is true, it stops when the condition becomes false.
a) True
b) False
View Answer
Explanation: While condition is true keep on looping.
2. What is the output of the given code?
counter = 1 while counter < 11 puts counter counter = counter + 1 end
a) Prints the number from 1 to 10
b) Prints the number from 1 to 11
c) Prints the number from 2 to 10
d) Infinite loop
View Answer
Explanation: Counter value is initialized to 1 and it keeps on looping till the counter is less than 11.
Output: 1 2 3 4 5 6 7 8 9 10
3. What is the output of the given code?
counter = true while counter !=false puts counter end
a) True
b) False
c) Syntax error
d) Infinite loop
View Answer
Explanation: Counter value is true in all cases hence true will be printed infinite times.
Output: true true ...Infinite loop
4. What is the output of the given code?
i = 0 while i < 5 puts i i=(i+1)**2 end
a) 1 2 3 4 5
b) 0 1 4
c) 0 1
d) 1 4
View Answer
Explanation: (i+1)**2 means i+1 to the power of 2 and hence the loop continues till i<5.
Output: 0 1 4
5. What is the output of the given code?
a=5 b=15 while a&&b puts a+b end
a) 5..15
b) 20
c) Infinite loop
d) 5 15
View Answer
Explanation: a && b will always be true so the looping will never come to an end.
Output: 20 20 ....infinite loop
6. What is the output of the given code?
a=5 b=15 while b>a puts a*(b-a) while a>b a+=1 b-=1 end end
a) 5..15
b) 50
c) Infinite loop
d) 5 50
View Answer
Explanation: b>a will always be true so the looping will never come to an end and as a>b will always be false it will never enter the other while loop.
Output: 50 50 ....infinite loop
7. What is the output of the given code?
i = 3 while i > 0 do print i i -= 1 end
a) 3
b) 321
c) Infinite loop
d) 3 2 1 0
View Answer
Explanation: The do statement here indicates that till the while condition is true execute the instructions.
Output: 321
8. What is the output of the given code?
i = 50 while i > 25 do print 50/i i -= 1 end
a) 50..25
b) 50..1
c) Infinite loop
d) 1111111111111111111111111
View Answer
Explanation: The do statement here indicates that till the while condition is true execute the instructions, so here it will print all the integer values of (50/i) which
will always be one.
Output: 1111111111111111111111111
9. What is the output of the given code?
a = 5 b=10 while a<b do puts a*b a+=2 b-=2 end
a) 5 10
b) 50 56
c) Infinite loop
d) 5 6 7 8 9 10
View Answer
Explanation: The do statement here indicates that till the while condition is true execute the instructions and will print a*b only till a
Output: 50 56