### Practical Exercises: Kotlin Programs
#### Exercise 1: Basic Structure, Loops, and If-Else
**Objective:** Familiarize with basic Kotlin syntax, control flow statements, and loops.
```kotlin
// Kotlin Program: Basic Structure, Loops, and If-Else
fun main() {
// Variables and Data Types
val name: String = "Kotlin Learner"
var age: Int = 20
println("Hello, $name! You are $age years old.")
// If-Else Statement
if (age < 18) {
println("You are a minor.")
} else {
println("You are an adult.")
}
// For Loop
println("For Loop: Counting from 1 to 5")
for (i in 1..5) {
println(i)
}
// While Loop
println("While Loop: Counting down from 5 to 1")
var count: Int = 5
while (count > 0) {
println(count)
count--
}
// Do-While Loop
println("Do-While Loop: Counting from 1 to 3")
var num: Int = 1
do {
println(num)
num++
} while (num <= 3)
}
**Tasks:**
- Run the program and observe the output.
- Modify the age variable and observe the change in output for the if-else statement.
#### Exercise 2: Functions
**Objective:** Learn how to define and use functions in Kotlin.
```kotlin
// Kotlin Program: Functions
fun main() {
// Calling a simple function
greetUser("Kotlin Learner")
// Calling a function with return value
val sumResult = addNumbers(5, 10)
println("Sum: $sumResult")
// Calling a function with default parameters
println("Area of rectangle: ${calculateArea(5.0, 3.0)}")
println("Area of square: ${calculateArea(4.0)}")
}
// Function to greet the user
fun greetUser(name: String) {
println("Hello, $name! Welcome to Kotlin Programming.")
}
// Function to add two numbers and return the result
fun addNumbers(a: Int, b: Int): Int {
return a + b
}
// Function with default parameters to calculate area
fun calculateArea(length: Double, width: Double = length): Double {
return length * width
}
```
**Tasks:**
- Run the program and observe the output.
- Experiment with different inputs for the `addNumbers` and `calculateArea` functions.
#### Exercise 3: Objects with Method Calls
**Objective:** Understand how to define classes and call methods between objects.
```kotlin
// Kotlin Program: Objects with Method Calls
fun main() {
// Creating an object of the Person class
val person1 = Person("John", 25)
val person2 = Person("Jane", 30)
// Calling methods on the objects
person1.introduce()
person2.introduce()
// Displaying the average age
val avgAge = calculateAverageAge(person1, person2)
println("Average Age: $avgAge")
}
// Defining the Person class
class Person(val name: String, var age: Int) {
// Method to introduce the person
fun introduce() {
println("Hi, I'm $name and I'm $age years old.")
}
}
// Function to calculate the average age of two persons
fun calculateAverageAge(p1: Person, p2: Person): Double {
return (p1.age + p2.age) / 2.0
}
```
**Tasks:**
- Run the program and observe the output.
- Create additional `Person` objects and use the `calculateAverageAge` function to find the average age of more people.