Kotlin for Loop
Kotlin for loop is used to iterate a part of program several times. It iterates through arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C#.
Syntax of for loop in Kotlin:
for (item in collection){
//body of loop
}
Iterate through array
Let's see a simple example of iterating the elements of array.
fun main(args : Array
val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}
Output:
80
85
60
90
70
If the body of for loop contains only one single line of statement, it is not necessary to enclose within curly braces {}.
fun main(args : Array
val marks = arrayOf(80,85,60,90,70)
for(item in marks)
println(item)
}
The elements of an array are iterated on the basis of indices (index) of array. For example:
fun main(args : Array
val marks = arrayOf(80,85,60,90,70)
for(item in marks.indices)
println("marks[$item]: "+ marks[item])
}
}
Output:
marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
Iterate through range
Let's see an example of iterating the elements of range.
fun main(args : Array
print("for (i in 1..5) print(i) = ")
for (i in 1..5) print(i)
println()
print("for (i in 5..1) print(i) = ")
for (i in 5..1) print(i)
// prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 5 downTo 2) print(i) = ")
for (i in 5 downTo 2) print(i)
println()
print("for (i in 1..5 step 2) print(i) = ")
for (i in 1..5 step 2) print(i)
println()
print("for (i in 5 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}
Output:
for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531
I NTRODUCTION TO OOP,CLASSES & OBJECTS 1. Use of scope Resolution of Operators. 2. Define a function outside a using scope resolution operators. 3. Write a program to calculate the area of circle, rectangle and square using function overloading. 4. Write a program to calculate the area of circle, rectangle and square using with class & object. 5. Write a program to demonstrate the use of returning a reference variable. 6. Create a class student,stores the details about name,roll no,marks of 5 subject,1.get function accept value of data members,2. display function to display,3.total function to return total of 5 subjects marks. 7. Create function power() in c++. & Create function power() in c++ and default argument. 8. Write a C++ program to swap the value of private data members from 2 different classes. 9. Write a program to illustrate the use of this pointer. 10. An election is contested by five candidates. The candidates are numbered 1 to 5 and the voting is do...
Comments
Post a Comment