Share
Explore

Introduction to Android Studio and Simple Kotlin Programming

If you just want to demonstrate simple Kotlin programs to show loops and if-then statements, you can use Android Studio as an IDE to write and run Kotlin scripts without creating a full Android app.

Steps to Write and Run Simple Kotlin Programs in Android Studio

Step 1: Create a Kotlin File

Open Android Studio.
Create a New Project (if you haven't already):
Start a new project and select "No Activity" to keep it simple.
Navigate to Project View:
On the left-hand side, switch to "Project" view to see the project directory structure.
Add a Kotlin File:
Right-click on the src folder (inside app/src/main/kotlin if the structure is like an Android project) or simply right-click on app.
Select New > Kotlin File/Class.
Name the file (e.g., SimpleKotlinProgram) and select "File" from the options.


Step 2: Write Your Kotlin Program

Open the Created Kotlin File (e.g., SimpleKotlinProgram.kt).
Write a Simple Program to Demonstrate Loops and If-Then Statements
fun main() { // Demonstrating a for loop var sum = 0 for (i in 1..10) { sum += i } println("The sum of numbers from 1 to 10 is: $sum")
// Demonstrating an if-then statement val number = 7 if (number % 2 == 0) { println("$number is even") } else { println("$number is odd") } }

Step 3: Run the Kotlin Program

Run the Program:
Right-click on the Kotlin file (e.g., SimpleKotlinProgram.kt).
Select Run 'SimpleKotlinProgramKt' from the context menu.
View the Output:
The output will be displayed in the Run window at the bottom of Android Studio.

Explanation of the Program

For Loop:
The for loop iterates from 1 to 10, adding each number to the variable sum.
After the loop, it prints the total sum.
If-Then Statement:
The if statement checks if the variable number is even or odd.
It uses the modulus operator % to check the remainder when number is divided by 2.
Depending on the result, it prints whether the number is even or odd.

Benefits

Focus on Basics: This method allows you to focus on teaching the basics of Kotlin without the complexity of Android app development.
Quick Feedback: Students get immediate feedback by running the program and seeing the output in the console.
Flexibility: You can easily modify the code to demonstrate other concepts such as different types of loops (while, do-while), nested loops, and more complex if-then-else conditions.

Additional Example

Nested Loop Example:
fun main() {
// Nested loops to print a multiplication table
for (i in 1..5) {
for (j in 1..5) {
print("${i * j}\t")
}
println()
}
}

image.png
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.