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
1 Write a shell script to execute following commands 1. Sort file abc.txt and save this sorted file in xyz.txt 2. Give an example of : To execute commands together without affecting result of each other. 3. How to print “this is a three –line 1. Text message” 4. Which command display version of the UNIX? 5. How would u get online help of cat command? echo “sorting the file” sort abc.txt > xyz.txt echo “executing two commands” who ; ls echo “this is \n a three-line \n Text message” # use -e option if required echo “The version is `uname -a`” echo “Help of cat command” man cat 2 Write a shell script to execute following commands 1. How would u display the hidden files? 2. How delete directory with files? 3. How would user can do interactive copying? 4. How would user can do interactive deletion of files? 5. Explain two functionality of “mv” command with example? echo “1. How would u display the hidden files” echo “2. How delete directory with files” echo...
Comments
Post a Comment