0% found this document useful (0 votes)
22 views9 pages

Practice Lab 2 MAD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views9 pages

Practice Lab 2 MAD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

DATE:20/12/24 NAME:M.

MAHESHWARI

EX.NO:PRACTICE-LAB-2 ROLL NO:22I329

KOTLIN PROGRAMS

1. Write a Kotlin program to count the frequency of each character in a string.

CODE:

fun main() {

print("Enter a string: ")

val input = readLine() ?: ""

val frequencyMap = mutableMapOf<Char, Int>()

for (char in input) {

if (char.isWhitespace()) continue

frequencyMap[char] = frequencyMap.getOrDefault(char, 0) + 1

println("Character frequencies:")

for ((char, count) in frequencyMap) {

println("$char: $count")

OUTPUT:
EXPLANATION:

Download the Kotlin 2.1.0 from github and extract it in the folder.Copy the path and store into the
program files of windows.Now check for Kotlin by kotlinc command in command prompt.Write the code
for frequency of characters and save it as .kt file.Compile by cmd: kotlinc charfreq.kt -include-runtime -
d charfreq.jar and after run by cmd:java -jar charfreq.jar. Now program will give output.

2. Convert uppercase letters to lowercase and vice versa in a string.

CODE:

fun main() {

print("Enter a string: ")

val input = readLine() ?: ""

val toggledString = input.map {

if (it.isUpperCase()) it.lowercaseChar()

else it.uppercaseChar()

}.joinToString("")

println("Toggled case string: $toggledString")

OUTPUT:

3. Write a Kotlin program to implement a basic currency converter. The program should:

1. Allow the user to select the source currency and the target currency (e.g., USD, EUR,INR).
2. Accept the amount in the source currency as input.
3. Convert the amount to the target currency based on predefined exchange rates.
4. Display the converted amount.
CODE:

fun main() {

val exchangeRates = mapOf(

"USD" to mapOf("EUR" to 0.85, "INR" to 74.5),

"EUR" to mapOf("USD" to 1.18, "INR" to 88.0),

"INR" to mapOf("USD" to 0.013, "EUR" to 0.011)

println("Available currencies: USD, EUR, INR")

print("Enter source currency: ")

val sourceCurrency = readLine()?.uppercase() ?: ""

print("Enter target currency: ")

val targetCurrency = readLine()?.uppercase() ?: ""

if (sourceCurrency !in exchangeRates || targetCurrency !in exchangeRates[sourceCurrency]!!) {

println("Invalid currency selection.")

return

print("Enter amount in $sourceCurrency: ")

val amount = readLine()?.toDoubleOrNull()

if (amount == null || amount <= 0) {

println("Invalid amount entered.")

return

}
val conversionRate = exchangeRates[sourceCurrency]!![targetCurrency]!!

val convertedAmount = amount * conversionRate

println("$amount $sourceCurrency is equal to ${"%.2f".format(convertedAmount)} $targetCurrency")

OUTPUT:

4. Implement Guess the number Game. The program randomly generates a number between 1

and 100. The player has to guess the number, and the program provides hints like”too high”

or “too low”. The game ends when the player guesses the correct number.

CODE:

import kotlin.random.Random

fun main() {

val randomNumber = Random.nextInt(1, 101)

var guess: Int?

var attempts = 0

println("Welcome to 'Guess the Number' Game!")

println("I'm thinking of a number between 1 and 100. Can you guess it?")

do {

print("Enter your guess: ")

guess = readLine()?.toIntOrNull()
if (guess == null || guess < 1 || guess > 100) {

println("Please enter a valid number between 1 and 100.")

continue

attempts++

when {

guess < randomNumber -> println("Too low! Try again.")

guess > randomNumber -> println("Too high! Try again.")

else -> println("Congratulations! You guessed the number in $attempts attempts.")

} while (guess != randomNumber)

println("Thanks for playing! The game is now over.")

OUTPUT:
5.Implement simple Login page using Kotlin.

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:padding="16dp">

<EditText

android:id="@+id/editTextUsername"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Username"

android:inputType="text" />

<EditText

android:id="@+id/editTextPassword"

android:layout_width="match_parent"

android:layout_height="wrap_content"
android:hint="Password"

android:inputType="textPassword"

android:layout_marginTop="8dp" />

<Button

android:id="@+id/buttonLogin"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Login"

android:layout_marginTop="16dp" />

</LinearLayout>

-----------

MainActivity.kt

package com.example.loginpage

import android.os.Bundle

import android.widget.Button

import android.widget.EditText

import android.widget.Toast

import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

// Get references to the UI elements

val usernameEditText = findViewById<EditText>(R.id.editTextUsername)


val passwordEditText = findViewById<EditText>(R.id.editTextPassword)

val loginButton = findViewById<Button>(R.id.buttonLogin)

// Set click listener for the Login button

loginButton.setOnClickListener {

val username = usernameEditText.text.toString()

val password = passwordEditText.text.toString()

if (username.isEmpty() || password.isEmpty()) {

Toast.makeText(this, "Please enter both username and password",


Toast.LENGTH_SHORT).show()

} else if (username == "admin" && password == "password") {

Toast.makeText(this, "Login Successful!", Toast.LENGTH_SHORT).show()

} else {

Toast.makeText(this, "Invalid Username or Password", Toast.LENGTH_SHORT).show()

You might also like