Chapter 3 - Algorithms and Programming Fundamentals
3.1 Variables, Data Types, and User Input
Every app needs a way to remember things—whether it’s a username, a score, or the time of the last login. Just like a backpack holds your books, an app needs containers to hold information. In programming, these containers are called variables.
In this section, you’ll learn how to use variables, understand different data types, and accept user input in your apps. These are the first building blocks of programming—once you’ve got them down, you can start making your app interactive and dynamic.
What Is a Variable?
A variable is like a labeled storage box that your app uses to remember information. When the user types in their name, answers a quiz question, or earns points, that information is saved in a variable.
In Kotlin, the programming language used in Android Studio, you create a variable using either val
or var
:
val name = "Jada"var score = 0
val
creates a constant variable—it can’t change once it’s set. You use this when the value is meant to stay the same.var
creates a mutable variable—it can change during the app’s runtime. This is useful for things like scores, levels, or settings that update.
Think of val
as a label on a locked box, and var
as a label on a box you can open and change as needed.
Understanding Data Types
Every variable holds a specific type of data. That type tells the computer how to store, use, and display the value. Here are the most common data types you’ll use when creating apps:
Data Type | What It Stores | Example |
---|---|---|
String | Text (letters, words, sentences) | "Hello" , "Math Quiz" |
Int | Whole numbers | 7 , 100 , -2 |
Double | Decimal numbers | 3.14 , 72.5 |
Boolean | True or False | true , false |
When declaring variables, Kotlin can usually figure out the type automatically. But sometimes, you’ll want to be specific:
val temperature: Double = 98.6val isLoggedIn: Boolean = false
By knowing the data type, the app knows how to format it, calculate with it, or check for conditions (like comparing numbers or displaying text).
Working with User Input
What makes an app truly interactive is letting the user provide their own data. Maybe they type in their name, select a setting, or choose a quiz answer. That’s called user input, and your app will need to handle it correctly.
In Android Studio, when you create a screen in your app layout, you might add an input field like this in XML:
<EditText android:id="@+id/nameInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter your name" />
This adds a field where the user can type their name. In your Kotlin code, you can capture the text they enter like this:
val name = findViewById<EditText>(R.id.nameInput).text.toString()
Now, the app stores the user’s input in a variable called name
. You can use this variable to greet the user, save it for later, or even personalize the app:
greetingText.text = "Welcome, $name!"
When you work with numbers, you may need to convert the input from text (String
) to an integer (Int
) or decimal (Double
):
val age = ageInput.text.toString().toInt()
It’s important to make sure the input is valid—what if the user didn’t type anything or entered letters instead of numbers? That’s where conditionals come in (and you’ll learn about those in the next section).
Using Variables in Your App
Let’s say you’re designing a quiz app. You might need variables for:
- The user’s name →
val userName: String
- The current question number →
var questionIndex: Int
- The number of correct answers →
var score: Int
- Whether the quiz is complete →
var isFinished: Boolean
Once these variables are set, you can use them to:
- Change the screen’s content
- Store and compare answers
- Show progress and feedback
- Track the user’s results
Variables are at the core of your app’s logic. Without them, your app would show the same thing to every user, every time. With them, your app becomes personal, smart, and responsive.
Best Practices for Working with Variables
- Use clear, descriptive names. Instead of
x
, useuserScore
,userName
, ortotalTasks
. - Avoid overwriting variables accidentally. Be careful where and how often you change values.
- Initialize variables before using them. Always make sure the app knows what a variable starts as.
- Keep track of your types. A number (
Int
) is not the same as text (String
), and mixing them up can cause bugs.
Conclusion
Variables may seem simple, but they are the foundation of all programming logic. Whether you’re creating a simple calculator, a to-do list, or a multiplayer game, you’ll use variables to store and manage everything your app knows.
In your project, try thinking ahead:
- What information does your app need to remember?
- Where will that information come from?
- How will you use it to make the app respond to users?
Once you can answer those questions, you’re well on your way to programming something amazing.
3.2 Conditionals, Loops, and Functions
Once your app can collect data from the user and store it in variables, the next step is to make the app respond to that data. Apps that just sit there showing static text aren’t very interesting. But apps that react—changing what they show, doing something different when a button is clicked, or repeating actions based on user choices—are dynamic and interactive.
That’s where conditionals, loops, and functions come in.
These are the core tools used to create logic in your app—what developers call the app’s behavior. You’ll learn how to use these tools to control how your app reacts to data, handles multiple actions, and keeps your code organized.
Conditionals: Making Decisions with If/Else
Imagine your app lets users take a quiz. After answering a question, the app needs to check if the answer is right or wrong—and respond differently depending on the result.
That’s called a conditional—a way of making decisions using if
statements.
Here’s the basic idea in Kotlin:
if (score >= 5) { feedbackText.text = "Great job!"} else { feedbackText.text = "Keep practicing!"}
In this example:
- If the condition is true (
score >= 5
), the app displays one message. - If it’s false, it shows another.
You can also use else if
to check multiple conditions:
if (score == 10) { feedbackText.text = "Perfect score!"} else if (score >= 7) { feedbackText.text = "Well done!"} else { feedbackText.text = "Try again!"}
This is how your app reacts intelligently to user input.
Use conditionals when:
- You want to check if a field is empty
- You want to validate a password or login
- You want to show or hide buttons or messages
- You want to update the screen based on the user’s data
When Statements: Cleaner Alternatives
Kotlin also has a special type of conditional called when
, which is like a more readable version of a long list of if...else
statements.
when (grade) { "A" -> resultText.text = "Awesome!" "B" -> resultText.text = "Good!" "C" -> resultText.text = "Keep working!" else -> resultText.text = "Let’s review!"}
This is great when you’re checking for many different values of one variable—like grades, choices, or answers.
Loops: Repeating Actions
Sometimes you need your app to repeat something—like going through a list of items, displaying multiple quiz questions, or counting up to a goal. That’s where loops come in.
There are two main types of loops you’ll use in Kotlin:
1. For Loops
for
loops run a block of code a certain number of times.
for (i in 1..5) { println("This is question $i")}
This loop prints a message five times, once for each value from 1 to 5. You can use this to:
- Show each item in a list
- Add multiple buttons or views to a screen
- Count something in the background
2. While Loops
while
loops keep running as long as a condition is true.
var score = 0
while (score < 100) { score += 10}
This loop increases the score by 10 until it reaches 100. Use while
loops when you don’t know exactly how many times something needs to run, but you do know what condition should end it.
Functions: Reusing Code with Purpose
As your app grows, your code will start to get longer. Instead of writing the same actions over and over again, you can organize your logic into functions.
A function is like a mini-program inside your app that does one specific job. You write it once, then use (or “call”) it whenever you need it.
Here’s a basic function in Kotlin:
fun greetUser(name: String) { println("Hello, $name!")}
This function takes in a String
and prints a greeting. You can call it like this:
greetUser("Jordan")
Functions are useful when:
- You want to run the same logic on multiple screens
- You need to clean up or organize long sections of code
- You want to make your code easier to debug or update later
Example: Quiz Feedback Function
Let’s say your app checks whether a quiz answer is right or wrong:
fun checkAnswer(userAnswer: String, correctAnswer: String): Boolean { return userAnswer == correctAnswer}
Now, instead of writing the same comparison over and over, you just call:
val isCorrect = checkAnswer("B", "C")
Functions save time, prevent mistakes, and help make your app more scalable.
Putting It All Together
Let’s say you’re building a simple math quiz app. Here’s how these concepts might work in combination:
- The app asks 5 questions using a loop
- For each question, it checks the answer using a conditional
- It keeps track of the score using a variable
- At the end, it uses a function to show a message based on the score
Suddenly, your app is making decisions, repeating actions, and giving feedback—all because you combined logic with structure.
Best Practices for Writing Clean Logic
- Keep your functions short. If it’s longer than 15 lines, break it into smaller ones.
- Name your functions clearly. Use names like
checkAnswer()
orupdateScore()
. - Use indentation and spacing. It makes code easier to read and debug.
- Test often. Add
println()
statements to check what’s happening as your app runs.
Conclusion
Conditionals, loops, and functions are the building blocks of all app logic. With these tools, you’re no longer just designing the way your app looks—you’re programming the way it thinks.
As you start creating interactive apps, keep asking yourself:
- What decision is the app making here?
- What needs to repeat?
- How can I simplify this with a function?
With just a few lines of logic, you can make your app smart, responsive, and ready for the real world.
3.3 Lists and Arrays
So far, you’ve worked with variables that store just one piece of information at a time—like a name, a score, or a user’s answer. But real apps usually need to keep track of many values at once.
Imagine your app is a task manager. You don’t just store one task—you store a list of tasks. If it’s a quiz app, you store multiple questions, answers, and scores. If it’s a budgeting app, you keep track of a collection of purchases.
That’s where lists and arrays come in.
In this section, you’ll learn how to group related pieces of data, access them efficiently, and use them in loops, displays, and logic. This is one of the biggest steps toward building a real, working app.
What Is a Collection?
In programming, a collection is a structure that holds multiple values in one place. The two most common types of collections in Kotlin are:
- Arrays – fixed-size lists of items
- Lists – flexible-size, more powerful structures
Let’s start with arrays, then explore lists, which are more commonly used in Android development.
Arrays: Fixed-Size Collections
An array is like a row of boxes. Each box holds a value, and each one has a number (called an index) that lets you find or change it.
Here’s how to make an array in Kotlin:
val colors = arrayOf("Red", "Blue", "Green")
You can access a specific item using its index (starting at 0):
val firstColor = colors[0] // Redval secondColor = colors[1] // Blue
Arrays are useful when:
- You know how many items you’ll have
- The list won’t change in size
- You’re working with performance-sensitive code (like games or animations)
However, in most apps, the data grows or shrinks over time. That’s when you use lists.
Lists: Flexible and Easy to Use
Kotlin makes working with lists very easy, especially using the mutableListOf()
function. Unlike arrays, lists can grow and shrink as your app runs.
val tasks = mutableListOf("Math Homework", "Science Project")
You can:
- Add a new item:
tasks.add("English Essay")
- Access an item:
val firstTask = tasks[0]
- Remove an item:
tasks.remove("Math Homework")
- Check the size of the list:
val numberOfTasks = tasks.size
- Loop through the items:
for (task in tasks) { println(task)}
Lists are everywhere in real-world apps:
- A list of recent messages
- A list of users or followers
- A list of saved locations, scores, items in a cart, etc.
When to Use Lists vs. Arrays
Use Lists When… | Use Arrays When… |
---|---|
You need to add/remove items often | You know the exact number of items |
Your app grows and changes during use | You’re managing performance in animations or games |
You want to use higher-level list functions | You want simpler, faster, more lightweight code |
Using Lists in Real Apps
Let’s imagine you’re designing a study flashcard app.
- Each flashcard has a front (question) and back (answer).
- You’ll need a list of questions and a list of answers.
- You’ll loop through the list when users tap “Next”.
Example:
val questions = listOf("What is 2 + 2?", "What is the capital of France?")val answers = listOf("4", "Paris")
You can display the current question like this:
val currentQuestion = questions[questionIndex]questionText.text = currentQuestion
When the user taps “Next”, you increase questionIndex
by 1 and load the next item.
This type of structure is the core of data-driven screens—where your layout changes based on the data in a list.
Modifying Lists with User Input
Let’s say your app allows users to create their own tasks. You can take input from a text field and add it to the list like this:
val newTask = taskInput.text.toString()tasks.add(newTask)
Then you update the screen (like refreshing a RecyclerView
) to show the updated list.
This kind of interaction—user input that changes a list—is exactly what powers modern apps. You’ll start small (adding tasks or quiz answers), but eventually this can grow into managing comments, social posts, or game objects.
Nested Collections and Advanced Uses
You can even store more complex data inside lists, like:
- Lists of numbers:
val scores = listOf(80, 90, 75)
- Lists of booleans:
val completed = listOf(true, false, false)
- Lists of custom objects (you’ll learn about this later in object-oriented programming)
You can also nest collections, such as a list of lists:
val quiz = listOf( listOf("Question 1", "Answer 1"), listOf("Question 2", "Answer 2"))
This is useful for things like tables, menus, and question banks.
Collections and User Experience
Using collections doesn’t just help organize your code—it also helps make your app smarter and more responsive.
For example:
- You can show “You have 3 remaining tasks” using
tasks.size
- You can disable a “Next” button when the user reaches the end of the list
- You can sort, filter, and group list items to make the app easier to use
When you combine lists with loops and conditionals, you unlock powerful features like custom animations, notifications, sorting, and live data updates.
Conclusion
Lists and arrays let your app do more than just store one value—they allow your app to think in groups, handle real user content, and scale as your user base grows. Whether you’re building a to-do list, quiz, game, or gallery, collections are a must.
You’re no longer writing apps that show a single message—you’re writing apps that adapt to multiple users, changing content, and complex features.
In the next section, you’ll learn how to make your app even more dynamic by adding randomness and simulations—turning your logic into something that can surprise, challenge, or even model real-world behavior.
3.4 Simulations and Random Values
So far, you’ve learned how to collect input, store data, use logic to make decisions, repeat actions with loops, and manage collections of data using lists. Now it’s time to introduce a little unpredictability—and fun—into your app. This is where random values and simulations come in.
Whether you’re building a game, quiz, or educational tool, randomness can help make your app feel more dynamic. And when you want to test different outcomes or model real-world behavior—like how fast a rumor spreads, or how many people win a prize—you can use a simulation.
This section shows how to use randomness in your code and how simulations can help your app do more than just repeat fixed responses.
What Is a Random Value?
A random value is a number or choice generated without a predictable pattern. When your app uses randomness, it can do things like:
- Pick a random quiz question
- Roll digital dice
- Generate a random event (like weather or loot)
- Shuffle the order of flashcards
In Kotlin, creating random values is simple:
val randomNumber = (1..10).random()
This creates a random integer between 1 and 10. You can also choose random items from a list:
val colors = listOf("Red", "Blue", "Green")val chosenColor = colors.random()
Randomness makes your app feel less scripted and more exciting—especially in games, learning apps, or anything that benefits from variety.
Using Randomness in Apps
Let’s explore a few examples of how random values can be used in real apps:
🎲 Dice Roller App
You can simulate rolling a six-sided die:
val roll = (1..6).random()diceText.text = "You rolled a $roll"
📚 Random Flashcard Picker
If your app includes a list of flashcards, you can show a random one:
val flashcards = listOf("Term 1", "Term 2", "Term 3")val selected = flashcards.random()flashcardText.text = selected
🎯 Mini Game Generator
Want to build a game that gives users random challenges?
val challenges = listOf("Jump 10 times", "Do 5 push-ups", "Solve a riddle")val challenge = challenges.random()challengeText.text = challenge
When combined with conditionals, you can also react differently based on the outcome of a random value. This is the foundation of simulations.
What Is a Simulation?
A simulation is when your app models a real or imaginary situation using data, rules, and sometimes randomness. Instead of just showing facts, your app simulates what might happen in different scenarios.
Simulations help users:
- Predict what could happen
- Explore cause and effect
- Learn through experimentation
Unlike a typical app feature that shows the same result every time, a simulation reacts to changing inputs and sometimes random variation.
Examples of Simple Simulations
📈 Coin Toss Probability
Flip a coin 100 times and see how often it lands on heads or tails:
var heads = 0var tails = 0
for (i in 1..100) { val flip = (1..2).random() if (flip == 1) heads++ else tails++}
resultText.text = "Heads: $heads, Tails: $tails"
This simulation shows that randomness can still have patterns over time.
👥 Spread of a Rumor
Simulate how fast a message spreads among students:
var studentsReached = 1var day = 0
while (studentsReached < 100) { studentsReached *= 2 day++}
resultText.text = "Rumor spread in $day days"
You’re using loops, math, and variables to simulate growth or change.
💸 Savings Growth
Model how a student saving $10 per week will reach $500:
var savings = 0var weeks = 0
while (savings < 500) { savings += 10 weeks++}
resultText.text = "It will take $weeks weeks to save $500"
This shows real-world outcomes using basic math and repetition.
Why Simulations Matter
Simulations aren’t just fun—they’re powerful. They help your app move beyond static behavior and become a tool for learning, planning, or predicting.
In real life, simulations are used to:
- Predict weather patterns
- Test traffic systems
- Train pilots or doctors
- Forecast business trends
- Explore science concepts (like evolution, population growth, or physics)
As an app creator, you can use simulations to:
- Build science or math games
- Show outcomes based on different choices
- Teach financial literacy
- Practice goal-setting or habit tracking
Even simple simulations show users something new—and give them control to explore how different inputs lead to different outcomes.
How to Build a Simple Simulation
To create a simulation, follow this pattern:
- Start with a situation (e.g., number of coins, number of players)
- Define the rules (e.g., how money grows, how users interact)
- Use loops and variables to repeat or update
- Add random values (if needed) to show variation
- Display the results
This process reinforces everything you’ve learned so far:
- Variables to store values
- Loops to simulate time or repetition
- Conditionals to make decisions
- Lists to track multiple results
- Random values to add unpredictability
Final Thoughts
With randomness and simulations, you’re not just building apps—you’re creating experiences. You’re teaching users, entertaining them, and helping them make discoveries. These tools bring your app to life.
As you continue coding, ask yourself:
- What happens if I make this random?
- How could I simulate a real-world process?
- What choices can I give the user to change the outcome?
These questions turn your app into a dynamic system, not just a collection of screens.
In the next chapter, you’ll begin connecting everything you’ve built so far across multiple screens and user sessions—making your app feel more like a real product and less like a prototype.
Discussion Prompt
“Think about a real app or game you’ve used that feels interactive, smart, or surprising. What do you think is happening in the background? How might that app use variables, loops, lists, conditionals, or random values to respond to your actions?”
Now imagine you are designing your own interactive feature—maybe a quiz, a mini game, a daily tracker, or a random generator.
- What data does your feature need to remember?
- What decisions will it make using conditionals?
- Will it use a loop to repeat something?
- Could randomness make it more fun or useful?
- How would you organize your data using a list?
Share your ideas in a small group or class discussion. Then describe how logic and algorithms could help bring your idea to life.
Key Vocabulary
Term | Definition |
---|---|
Variable | A container used in code to store information like numbers, text, or true/false values. |
Data Type | The kind of value a variable holds, such as String (text), Int (number), or Boolean . |
User Input | Information entered by the user into the app, such as typing in a name or selecting a choice. |
Conditional | A programming structure (like if or when ) that lets the app make decisions based on data. |
Loop | Code that repeats an action multiple times, like using a for or while loop. |
Function | A named block of code that performs a specific task and can be reused throughout the app. |
Array | A fixed-size collection that holds multiple items of the same type, accessed by index. |
List | A flexible collection that can grow or shrink, used to store multiple values in order. |
Index | The position number of an item in a list or array, starting at 0. |
Random Value | A value generated unpredictably, often used in games or simulations to add variety. |
Simulation | A model that mimics real-world behavior using logic, loops, and sometimes random values. |
Algorithm | A step-by-step set of instructions that solves a problem or performs a task. |
Boolean | A data type that stores only true or false values, often used in conditionals. |