Skip to content

Instantly share code, notes, and snippets.

@pradhuman-soni
Created November 26, 2021 10:12
Show Gist options
  • Select an option

  • Save pradhuman-soni/83fd260a89e9c237d09ce5ba3d08e588 to your computer and use it in GitHub Desktop.

Select an option

Save pradhuman-soni/83fd260a89e9c237d09ce5ba3d08e588 to your computer and use it in GitHub Desktop.
Kotlin Loops
Q. Why we use loops?
A. Loops are used when we need to do a task repeatedly till a condition satisfies.
Q. What is the use of continue?
A. Whenever we encounter a continue in a loop, all the lines of code below it are skipped and then it jumps back to the top.
Q. What is the use of break?
A. break is used to terminate a loop if a certain condition is encountered.
Q. What is the difference between while and do while loop?
A. while loop checks the condition first and then keeps executing till the condition is satisfied,
whereas do while executes first and then checks the condition that means that it will run at least once.
Q. Which one is a correct condition declaration to traverse an array arr?
a) for(i in arr) {---loop body---}
b) for(i in arr.indices) {---loop body---}
c) for((i,j) in arr.withIndex()) {---loop body---}
d) all of these
A. d) all of these
Q. What will be the output?
fun main() {
for (i in 1..10) {
if (i % 2 == 0){
continue
}
print("$i, ")
if (i >= 4) {
break
}
}
}
a) 1, 3,
b) 1, 3, 5,
c) 1, 3, 5, 7, 9,
d) None of These
A. b) 1, 3, 5,
Q. What will be the output?
fun main() {
var arr = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
for ((i, j) in arr.withIndex()) {
if (j == 3) continue
if (i == 5) break
print("$i, ")
}
}
a) 0, 1, 3, 4,
b) 0, 1, 2, 4,
c) 0, 1, 3, 4, 5,
d) 0, 1, 2, 4, 5,
A. a) 0, 1, 3, 4,
Q. What will be the output?
fun main(){
for(i in 1..2) {
print("loop range : $i-- ")
}
}
a) 1 2
b) 0 1
c) 1-- 2--
A. c) 1-- 2--
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment