Share
Explore

Programming KOTLIN up to OBJECTS

KOTLIN Programming Drill Exercises:

OO Programming : An Object has 3 Truths:
Data Fields
Behaviors/ code / Methods are the boxes you contain your code in
Unique IDENTITY - most languages support a method to report on the UUID
in KOTLIN can I print the uuid for a variable
In Kotlin, you can print the UUID of a variable using the toString() function on the UUID object. For example, given a UUID variable serviceUUID, you can print it as follows:
kotlinprintln(serviceUUID.toString())
Before printing, ensure that the variable holds a valid UUID value; otherwise, you might get an exception while printing it.
Regarding 10 , 11 , 21 , and 22 , they contain information primarily about generating and using UUIDs, but there is no direct relation to printing the UUID of a variable as asked in the question.
Upon reviewing 9 and 8 , they discuss generating UUIDs in Kotlin and Java, but there is no information about printing the UUID for a variable.
For 7 , it gives a recommendation of the UUID generation method in Kotlin, but it does not cover the print functionality of a UUID variable.
Lastly, 6 is related to generating UUIDs in Java, discussing string conversion and other options, but it does not include information about printing the UUID for a variable in Kotlin.

megaphone

### Introductory Preamble for Using an Online IDE

---
Welcome, everyone! Today, we're going to embark on an exciting journey into the world of Kotlin, and I couldn't be more thrilled to share this experience with you. Before we dive into the code, I want to take a moment to talk about why we'll be using an online IDE for our drills today.
Learning programming, especially a versatile and powerful language like Kotlin, can be an incredibly rewarding experience.
But we all know that the environment in which we learn plays a crucial role in how effectively we grasp new concepts. This is why I’ve chosen an online IDE for our class today. Here are some reasons why this approach will help you learn better and enjoy the process:
1. **Instant Setup**: One of the best things about online IDEs is that they require no setup. You can start coding right away without worrying about installing software or configuring your system. This means more time for learning and less time troubleshooting.
2. **Consistency**: Everyone will be working in the same environment, which ensures that we all have a consistent experience. This consistency means fewer technical issues and more focus on learning Kotlin.
3. **Accessibility**: You can access the online IDE from any device with an internet connection. Whether you're using a laptop, tablet, or even a smartphone, you can practice coding anywhere, anytime. This flexibility allows you to integrate learning into your daily life seamlessly.
4. **Collaboration**: Many online IDEs support collaborative features, which means you can work together with your peers in real-time. This collaborative environment fosters a sense of community and allows you to learn from each other’s experiences and insights.
5. **Immediate Feedback**: Online IDEs often provide immediate feedback on your code, which is crucial for learning. Instant feedback helps you understand mistakes as they happen, reinforcing learning and helping you to quickly correct errors.
6. **Fun and Engaging**: Using an online IDE can make the learning process more fun and engaging. The modern, user-friendly interfaces and interactive features are designed to keep you motivated and excited about coding.
Remember, people learn better when they are in a happy and enthused state. By using an online IDE, we eliminate many of the frustrations that can come with setting up a traditional development environment. Instead, we can focus our energy on exploring Kotlin, experimenting with code, and enjoying the process of learning something new.
So let's dive in with enthusiasm, knowing that we have the tools and the environment to make this a productive and enjoyable experience. Get ready to code, collaborate, and conquer Kotlin!
---

We will be using
image.png

Online IDEs suitable for teaching Kotlin, from basic syntax to more advanced concepts like objects. Here are a few options that you can use for your class:
1. JetBrains Academy (Hyperskill)
- **Link**: [JetBrains Academy](https://www.jetbrains.com/academy/) - **Features**: Provides a comprehensive learning platform with interactive projects and tasks. It covers Kotlin from basic syntax to advanced topics, including object-oriented programming. - **Advantages**: Developed by the creators of Kotlin, ensures up-to-date and accurate information.

### 2. **Kotlin Playground
- **Link**: [Kotlin Playground](https://play.kotlinlang.org/) - **Features**: An official Kotlin online compiler that supports writing, running, and sharing Kotlin code snippets. - **Advantages**: Simple and easy to use, perfect for demonstrating code and running examples in real-time.

### 3. **Repl.it
- **Link**: [Repl.it](https://replit.com/) - **Features**: Supports Kotlin and many other languages, allows for collaborative coding and sharing of projects. - **Advantages**: Provides an interactive environment, useful for both teaching and assignments. Students can see changes in real-time.

### 4. **Coding Rooms
- **Link**: [Coding Rooms](https://codingrooms.com/) - **Features**: An interactive platform for teaching programming. Supports live coding sessions, real-time feedback, and classroom management tools. - **Advantages**: Excellent for live classes, where you can monitor student progress and assist them in real-time.

### 5. **PaizaCloud Cloud IDE
- **Link**: [PaizaCloud Cloud IDE](https://paiza.cloud/en/) - **Features**: An online coding platform that supports Kotlin and other languages. It provides a Linux server environment with a graphical user interface. - **Advantages**: Great for more advanced setups where you might need a more full-fledged development environment.

ow to Use Kotlin Playground for Teaching
#### Step-by-Step Guide
1. **Open Kotlin Playground**: - Navigate to [Kotlin Playground]
(https://play.kotlinlang.org/).
2. **Basic Kotlin Program**: - Start with a simple "Hello, World!" program. ```kotlin fun main() { println("Hello, World!") } ``` - Run the code by clicking the green "Run" button.
3. **Teaching Object-Oriented Concepts**: - **Classes and Objects**: ```kotlin class Person(val name: String, val age: Int)
fun main() { val person = Person("Alice", 30) println("Name: ${person.name}, Age: ${person.age}") } ``` - **Inheritance**: ```kotlin open class Animal(val name: String) { fun makeSound() { println("$name makes a sound.") } }
class Dog(name: String) : Animal(name) { fun bark() { println("$name barks.") } }
fun main() { val dog = Dog("Buddy") dog.makeSound() dog.bark() } ``` - **Interfaces**: ```kotlin interface Drivable { fun drive() }
class Car(val make: String, val model: String) : Drivable { override fun drive() { println("Driving a $make $model") } }
fun main() { val car = Car("Toyota", "Corolla") car.drive() } ```

Conclusion

Using an online IDE like Kotlin Playground or Repl.it allows you to easily demonstrate Kotlin concepts, from basic syntax to object-oriented programming.
These platforms are user-friendly and perfect for a classroom setting where students can follow along and run their own code.

Outline for a Graduated Series of Kotlin Programming Labs


Lab 1: Introduction to Kotlin and Variable Assignments

- **Objective**: Understand the basics of Kotlin and how to declare and use variables.
- **Topics Covered**:
- Introduction to Kotlin
- Setting up the Kotlin environment (using an online IDE)
- Variable declarations (var vs val) - Basic data types (Int, String, Boolean, etc.) - **Exercises**: - Declare and initialize various types of variables. - Perform basic arithmetic operations and string concatenation.
### Lab 1: Introduction to Kotlin and Variable Assignments

#### Objective:
Understand the basics of Kotlin and how to declare and use variables.

#### Topics Covered:
- Introduction to Kotlin
- Setting up the Kotlin environment (using an online IDE)
- Variable declarations (var vs val)
- Basic data types (Int, String, Boolean, etc.)

#### Exercises:

1. **Variable Declaration and Initialization**
- Declare a mutable variable (var) and assign it an integer value.
- Declare an immutable variable (val) and assign it a string value.

```kotlin
var age: Int = 25
val name: String = "Alice"
```

2. **Basic Arithmetic Operations**
- Create two integer variables and perform addition, subtraction, multiplication, and division. Print the results.

```kotlin
var num1: Int = 10
var num2: Int = 5

println("Addition: ${num1 + num2}")
println("Subtraction: ${num1 - num2}")
println("Multiplication: ${num1 * num2}")
println("Division: ${num1 / num2}")
```

3. String Concatenation
- Declare two string variables and concatenate them. Print the concatenated string.

val firstName: String = "John"
val lastName: String = "Doe"
val fullName: String = firstName + " " + lastName

println("Full Name: $fullName")
```

4. Boolean Variables TRUE False

Declare a boolean variable and assign it a value. Print the value.

val isKotlinFun: Boolean = true
println("Is Kotlin fun? $isKotlinFun")
5. Type Inference :
- Declare variables without specifying their types and let Kotlin infer the types.

var city = "Toronto"
var temperature = 20.5

println("City: $city")
println("Temperature: $temperature")

6. Reassigning Variables
- Declare a mutable variable, assign it a value, then reassign it a new value. Print both values.

```kotlin
var score: Int = 50
println("Initial Score: $score")

score = 75
println("Updated Score: $score")
```

7. **Arithmetic with Variables**
- Declare three integer variables and calculate their average. Print the result.

```kotlin
var a: Int = 5
var b: Int = 10
var c: Int = 15
var average: Int = (a + b + c) / 3

println("Average: $average")
```

8. **String Templates**
- Use string templates to include variables within a string. Print the formatted string.

```kotlin
val product: String = "Laptop"
val price: Double = 999.99

println("The price of the $product is $$price")
```

9. **Combining Different Data Types**
- Declare variables of different data types and print a sentence that includes all the variables.

val item: String = "book"
val quantity: Int = 3
val pricePerItem: Double = 12.99

println("You bought $quantity $item(s) for a total of $${quantity * pricePerItem}")

10. **Understanding Nullability**
- Declare a nullable variable and assign it a value. Change the value to null and print both states.

```kotlin
var nullableName: String? = "Kotlin"
println("Name: $nullableName")

nullableName = null
println("Name after null assignment: $nullableName")
```

By completing these exercises, students will get hands-on experience with variable declarations, type inference, basic operations, and more, providing a solid foundation for their journey in learning Kotlin.

megaphone

Distinguishing val and var

### Lab: Understanding `val` and `var` in Kotlin
#### Objective: Learn the distinctions between `val` and `var` in Kotlin and understand when to use each for declaring variables.
Topics Covered: - Immutable variables (`val`) like const: not changable - Mutable variables (`var`) change / reassign - Differences between `val` and `var` - Practical use cases for `val` and `var`

1. **Declaring `val` and `var`** - Declare a variable using `val` and another using `var`. Assign initial values and try to reassign new values. Observe the results.
```kotlin // Immutable variable (val) val pi = 3.14 println("Initial value of pi: $pi")
// Uncommenting the next line will cause a compilation error // pi = 3.14159
// Mutable variable (var) var age = 25 println("Initial age: $age")
// Reassigning a new value to the mutable variable age = 26 println("Updated age: $age") ```
2. **Using `val` for Constants** - Use `val` to declare a constant value that should not change throughout the program.
```kotlin val appName = "My Kotlin App" println("Application Name: $appName")
// Uncommenting the next line will cause a compilation error // appName = "New App Name" ```
3. **Using `var` for Mutable Data** - Use `var` to declare a variable whose value will change during the program execution.
```kotlin var counter = 0 println("Initial counter value: $counter")
// Incrementing the counter counter += 1 println("Updated counter value: $counter") ```
4. Scope of `val` and `var` in Loops - Use `val` and `var` inside a loop to understand their behavior within the loop scope.
```kotlin for (i in 1..5) { val immutableLoopValue = i var mutableLoopValue = i mutableLoopValue += 10
println("Iteration $i: immutableLoopValue = $immutableLoopValue, mutableLoopValue = $mutableLoopValue") } ```
5. **Using `val` with Collections** - Declare a collection with `val` and try modifying the collection. Understand that `val` ensures the reference is immutable, not the contents.
```kotlin val fruits = mutableListOf("Apple", "Banana", "Cherry") println("Original fruits list: $fruits")
// Adding an element to the collection fruits.add("Date") println("Updated fruits list: $fruits")
// Uncommenting the next line will cause a compilation error // fruits = mutableListOf("Elderberry") ```
6. **Using `var` with Collections** - Declare a collection with `var` and modify the collection reference.
```kotlin var vegetables = mutableListOf("Carrot", "Broccoli", "Spinach") println("Original vegetables list: $vegetables")
// Modifying the collection vegetables.add("Pepper") println("Updated vegetables list: $vegetables")
// Reassigning the variable to a new collection vegetables = mutableListOf("Tomato", "Cucumber") println("Reassigned vegetables list: $vegetables") ```
7. **Behavior of `val` and `var` with Objects** - Create a class and use `val` and `var` to declare properties. Understand the difference in behavior.
```kotlin class Person(val name: String, var age: Int)
val person = Person("Alice", 30) println("Person: ${person.name}, Age: ${person.age}")
// Uncommenting the next line will cause a compilation error // person.name = "Bob"
// Modifying the mutable property person.age = 31 println("Updated Age: ${person.age}") ```
8. **Using `val` for Read-Only Properties** - Declare a read-only property in a class using `val`.
```kotlin class Circle(val radius: Double) { val area: Double get() = 3.14 * radius * radius }
val circle = Circle(5.0) println("Circle radius: ${circle.radius}, Area: ${circle.area}")
// Uncommenting the next line will cause a compilation error // circle.radius = 6.0 ```
9. **Using `var` for Read-Write Properties** - Declare a read-write property in a class using `var`.
```kotlin class Rectangle(var length: Double, var width: Double) { var area: Double get() = length * width set(value) { length = value / width } }
var rectangle = Rectangle(4.0, 5.0) println("Rectangle length: ${rectangle.length}, width: ${rectangle.width}, area: ${rectangle.area}")
// Modifying the properties rectangle.length = 6.0 println("Updated length: ${rectangle.length}, width: ${rectangle.width}, area: ${rectangle.area}") ```
10. **Understanding `val` in Function Parameters** - Use `val` in function parameters to ensure the parameters cannot be reassigned within the function.
```kotlin fun printMessage(message: String) { println("Message: $message")
// Uncommenting the next line will cause a compilation error // message = "New Message" }
printMessage("Hello, Kotlin!") ```
By completing these exercises, students will gain a solid understanding of the differences between `val` and `var` in Kotlin, and they will learn when to use each for declaring variables.

Let’s see how to run these functions from the `main` function.

Let’s illustrate variable visibility from one context (global / function / object) to another.
### Lab: Understanding Variable Scope in Kotlin
#### Objective: Learn about variable scope in Kotlin by exploring different contexts and how scoping rules affect variable visibility and lifetime.
#### Topics Covered: - Local scope - Function scope - Block scope (if, for, while) - Class scope - Object scope
#### Exercises:
1. **Local Scope** - Variables declared inside a function are local to that function and cannot be accessed outside it.
```kotlin fun localScopeExample() { val localVar = "I am local" println(localVar) }
fun main() { localScopeExample()
// Uncommenting the next line will cause a compilation error // println(localVar) } ```
2. **Function Scope** - Variables declared inside a function are only accessible within that function.
```kotlin fun functionScopeExample() { val functionVar = "Inside function" println(functionVar) }
fun main() { functionScopeExample()
// Uncommenting the next line will cause a compilation error // println(functionVar) } ```
3. **Block Scope (if)** - Variables declared inside an if block are only accessible within that block.
```kotlin fun blockScopeIfExample() { val condition = true
if (condition) { val blockVar = "Inside if block" println(blockVar) }
// Uncommenting the next line will cause a compilation error // println(blockVar) }
fun main() { blockScopeIfExample() } ```
4. **Block Scope (for)** - Variables declared inside a for loop are only accessible within that loop.
```kotlin fun blockScopeForExample() { for (i in 1..5) { val loopVar = "Iteration $i" println(loopVar) }
// Uncommenting the next line will cause a compilation error // println(loopVar) }
fun main() { blockScopeForExample() } ```
5. **Block Scope (while)** - Variables declared inside a while loop are only accessible within that loop.
```kotlin fun blockScopeWhileExample() { var count = 0
while (count < 3) { val whileVar = "Count is $count" println(whileVar) count++ }
// Uncommenting the next line will cause a compilation error // println(whileVar) }
fun main() { blockScopeWhileExample() } ```
6. **Class Scope** - Variables declared inside a class but outside any function are accessible throughout the class.
```kotlin class ClassScopeExample { val classVar = "I am in the class"
fun printClassVar() { println(classVar) } }
fun main() { val example = ClassScopeExample() example.printClassVar()
// The following line will cause a compilation error because classVar is not accessible outside the class // println(example.classVar) } ```
7. **Object Scope** - Variables declared inside an object (singleton) are accessible throughout the object.
```kotlin object ObjectScopeExample { val objectVar = "I am in the object"
fun printObjectVar() { println(objectVar) } }
fun main() { ObjectScopeExample.printObjectVar()
// The following line will cause a compilation error because objectVar is not accessible directly // println(ObjectScopeExample.objectVar) } ```
8. **Nested Scopes** - Explore variable access in nested scopes (block within a block).
```kotlin fun nestedScopeExample() { val outerVar = "Outer"
if (true) { val innerVar = "Inner" println(outerVar) // Accessible println(innerVar) // Accessible }
// Uncommenting the next line will cause a compilation error // println(innerVar) }
fun main() { nestedScopeExample() } ```
9. **Shadowing** - Understand how variable shadowing works when a variable in an inner scope has the same name as one in an outer scope.
```kotlin val shadowVar = "Outer"
fun shadowingExample() { val shadowVar = "Inner" println(shadowVar) // Prints "Inner" }
fun main() { println(shadowVar) // Prints "Outer" shadowingExample() }
10. **Extension Functions and Scope** - Explore scope within extension functions.
```kotlin fun String.printLength() { val length = this.length println("The length of '$this' is $length") }
fun main() { val message = "Hello, Kotlin!" message.printLength()
// Uncommenting the next line will cause a compilation error // println(length) } ```
By running these examples from the `main` function, students will see how variable scoping rules work in various contexts within Kotlin. Each function demonstrates a specific scoping rule, and the `main` function serves as the entry point for running these examples.
megaphone

Lab: Understanding Variable Scope in Kotlin

Learn about variable scope (when variables are visible or not in various contexts) in Kotlin by exploring different contexts and how scoping rules affect variable visibility and lifetime.
#### Topics Covered: - Local scope - Function scope - Block scope (if, for, while) - Class scope - Object scope
#### Exercises:
1. **Local Scope** - Variables declared inside a function are local to that function and cannot be accessed outside it.
```kotlin fun localScopeExample() { val localVar = "I am local" println(localVar) }
localScopeExample()
// Uncommenting the next line will cause a compilation error // println(localVar) ```
2. **Function Scope** - Variables declared inside a function are only accessible within that function.
```kotlin fun functionScopeExample() { val functionVar = "Inside function" println(functionVar) }
functionScopeExample()
// Uncommenting the next line will cause a compilation error // println(functionVar) ```
3. **Block Scope (if)** - Variables declared inside an if block are only accessible within that block.
```kotlin val condition = true
if (condition) { val blockVar = "Inside if block" println(blockVar) }
// Uncommenting the next line will cause a compilation error // println(blockVar) ```
4. **Block Scope (for)** - Variables declared inside a for loop are only accessible within that loop.
```kotlin for (i in 1..5) { val loopVar = "Iteration $i" println(loopVar) }
// Uncommenting the next line will cause a compilation error // println(loopVar) ```
5. **Block Scope (while)** - Variables declared inside a while loop are only accessible within that loop.
```kotlin var count = 0
while (count < 3) { val whileVar = "Count is $count" println(whileVar) count++ }
// Uncommenting the next line will cause a compilation error // println(whileVar) ```
6. **Class Scope** - Variables declared inside a class but outside any function are accessible throughout the class.
```kotlin class ClassScopeExample { val classVar = "I am in the class"
fun printClassVar() { println(classVar) } }
val example = ClassScopeExample() example.printClassVar()
// The following line will cause a compilation error because classVar is not accessible outside the class // println(example.classVar) ```
7. **Object Scope** - Variables declared inside an object (singleton) are accessible throughout the object.
```kotlin object ObjectScopeExample { val objectVar = "I am in the object"
fun printObjectVar() { println(objectVar) } }
ObjectScopeExample.printObjectVar()
// The following line will cause a compilation error because objectVar is not accessible directly // println(ObjectScopeExample.objectVar) ```
8. **Nested Scopes** - Explore variable access in nested scopes (block within a block).
```kotlin fun nestedScopeExample() { val outerVar = "Outer"
if (true) { val innerVar = "Inner" println(outerVar) // Accessible println(innerVar) // Accessible }
// Uncommenting the next line will cause a compilation error // println(innerVar) }
nestedScopeExample() ```
9. **Shadowing** - Understand how variable shadowing works when a variable in an inner scope has the same name as one in an outer scope.
```kotlin val shadowVar = "Outer"
fun shadowingExample() { val shadowVar = "Inner" println(shadowVar) // Prints "Inner" }
println(shadowVar) // Prints "Outer" shadowingExample() ```
10. **Extension Functions and Scope** - Explore scope within extension functions.
```kotlin fun String.printLength() { val length = this.length println("The length of '$this' is $length") }
val message = "Hello, Kotlin!" message.printLength()
// Uncommenting the next line will cause a compilation error // println(length) ```
By completing these exercises, students will gain a comprehensive understanding of variable scope in Kotlin and how it affects the visibility and lifetime of variables in various contexts.

Lab 2: Control Flow - Conditionals

- **Objective**: Learn how to control the flow of your program using conditional statements. - **Topics Covered**: - if-else statements - when expressions - **Exercises**: - Write programs that use if-else statements to make decisions. - Use when expressions to handle multiple conditions.

megaphone

### Lab 2: Control Flow - Conditionals

#### Objective: Learn how to control the flow of your program using conditional statements.
#### Topics Covered: - if-else statements - when expressions
#### Exercises:
1. **Basic if-else Statement** - Write a program that checks if a number is positive, negative, or zero. Print an appropriate message for each case.
```kotlin val number = 10
if (number > 0) { println("The number is positive") } else if (number < 0) { println("The number is negative") } else { println("The number is zero") } ```
2. **if-else with Boolean Conditions** - Write a program that checks if a person is eligible to vote (age >= 18). Print "Eligible to vote" or "Not eligible to vote".
```kotlin val age = 20
if (age >= 18) { println("Eligible to vote") } else { println("Not eligible to vote") } ```
3. **Nested if-else Statements** - Write a program that takes three integers and prints the largest number using nested if-else statements.
```kotlin val a = 5 val b = 10 val c = 7
if (a > b && a > c) { println("The largest number is $a") } else if (b > a && b > c) { println("The largest number is $b") } else { println("The largest number is $c") } ```
4. **if-else with String Comparison** - Write a program that compares two strings and prints whether they are equal or not.
```kotlin val str1 = "Kotlin" val str2 = "Kotlin"
if (str1 == str2) { println("The strings are equal") } else { println("The strings are not equal") } ```
5. **if-else with Logical Operators** - Write a program that checks if a number is within the range of 1 to 100 inclusive. Print "In range" or "Out of range".
```kotlin val number = 50
if (number >= 1 && number <= 100) { println("In range") } else { println("Out of range") }
6. **Simple when Expression** - Write a program that takes a day of the week as an integer (1 for Monday, 2 for Tuesday, etc.) and prints the corresponding day name using a when expression.
val day = 3
when (day) { 1 -> println("Monday") 2 -> println("Tuesday") 3 -> println("Wednesday") 4 -> println("Thursday") 5 -> println("Friday") 6 -> println("Saturday") 7 -> println("Sunday") else -> println("Invalid day") }
7. **when with Multiple Conditions** - Write a program that categorizes a given score into "Excellent", "Good", "Fair", or "Poor" using a when expression.
```kotlin val score = 85
when { score >= 90 -> println("Excellent") score >= 75 -> println("Good") score >= 50 -> println("Fair") else -> println("Poor") } ```
8. **when with Type Checking** - Write a program that uses a when expression to check the type of a given value (String, Int, Boolean) and prints a message based on the type.
```kotlin val value: Any = "Hello"
when (value) { is String -> println("It's a string") is Int -> println("It's an integer") is Boolean -> println("It's a boolean") else -> println("Unknown type") } ```
9. **when with Range Checking** - Write a program that uses a when expression to check if a number is in different ranges (e.g., 1-10, 11-20, 21-30) and prints the range it falls into.
```kotlin val number = 15
when (number) { in 1..10 -> println("The number is between 1 and 10") in 11..20 -> println("The number is between 11 and 20") in 21..30 -> println("The number is between 21 and 30") else -> println("The number is outside the range 1-30") } ```
10. **Combining if-else and when** - Write a program that takes an age and a country code ("US", "UK", "CA") and prints whether the person is eligible to drink alcohol.
The legal drinking age varies by country (e.g., 21 in the US, 18 in the UK and Canada).
```kotlin val age = 20 val country = "US"
val legalDrinkingAge = when (country) { "US" -> 21 "UK" -> 18 "CA" -> 18 else -> 0 }
if (age >= legalDrinkingAge) { println("Eligible to drink") } else { println("Not eligible to drink") } ```
These exercises cover various aspects of control flow using `if-else` statements and `when` expressions, providing a strong foundation in making decisions within a Kotlin program.


Lab 3: Control Flow - Loops** - **Objective**: Understand how to use loops to repeat actions. - **Topics Covered**: - for loops - while loops - do-while loops - **Exercises**: - Write loops to iterate over ranges and collections. - Implement programs that use loops to solve problems.
ok

### Lab 3: Control Flow - Loops

#### Objective: Understand how to use loops to repeat actions.
#### Topics Covered: - for loops - while loops - do-while loops
#### Exercises:
1. **For Loop with a Range** - Write a program that uses a for loop to print numbers from 1 to 10.
```kotlin fun main() { for (i in 1..10) { println(i) } } ```
2. **For Loop with a List** - Write a program that iterates over a list of fruits and prints each fruit.
```kotlin fun main() { val fruits = listOf("Apple", "Banana", "Cherry", "Date")
for (fruit in fruits) { println(fruit) } } ```
3. **For Loop with an Array** - Write a program that iterates over an array of integers and prints the square of each number.
```kotlin fun main() { val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) { println(number * number) } } ```
4. **While Loop** - Write a program that uses a while loop to print numbers from 10 down to 1.
```kotlin fun main() { var i = 10
while (i > 0) { println(i) i-- } } ```
5. **While Loop with User Input** - Write a program that uses a while loop to repeatedly ask the user for a number until they enter a negative number.
```kotlin fun main() { var number: Int
while (true) { print("Enter a number (negative to stop): ") number = readLine()?.toIntOrNull() ?: continue
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.