Putting it together
- Kotlin course
- Beginner
- Lesson 23/116
- 6 min
Combine all parts into a working calculator.
Putting it together: for loop
In the last step we'll add a for loop to the calculator. for (i in 0..2) counts from 0 to 2 (inclusive). Inside the loop we'll call add(i, i) to print 0, 2, 4.
for (i in 0..2) {
println(add(i, i))
}This completes the project: addition, subtraction, multiplication, division and a loop of calculations.
Practice Add the for loop
Inside the existing main, after the first println, add for (i in 0..2) { println(add(i, i)) }. Keep all other calls (subtract, multiply, try/catch with divide).
Starter code
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a - b
}
fun multiply(a: Int, b: Int): Int {
return a * b
}
fun divide(a: Int, b: Int): Int {
if (b == 0) {
return 0
}
return a / b
}
fun main() {
println("Calculator")
println(add(5, 3))
println(subtract(5, 3))
println(multiply(5, 3))
try {
println(divide(10, 2))
} catch (e: ArithmeticException) {
println("Division by zero")
}
}Sample solution
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a - b
}
fun multiply(a: Int, b: Int): Int {
return a * b
}
fun divide(a: Int, b: Int): Int {
if (b == 0) {
return 0
}
return a / b
}
fun main() {
println("Calculator")
for (i in 0..2) {
println(add(i, i))
}
println(subtract(5, 3))
println(multiply(5, 3))
try {
println(divide(10, 2))
} catch (e: ArithmeticException) {
println("Division by zero")
}
}Expected output
Calculator 0 2 4 2 15 5
Next step
Congratulations! You've completed the calculator project. Step by step you wrote a skeleton, added functions, used error handling, and ran several calculations in a loop.
In the next group you'll examine operators in detail: arithmetic, assignment, comparison, logical and the Elvis operator. These operators are the basic tools for writing calculations and conditions in code.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the project stages
| Term | Meaning |
|---|---|
L1 |
Skeleton |
L2 |
add, subtract |
L3 |
multiply, divide |
L4 |
try/catch |
2 for loop
for (i in 0____2) {
println(add(i, i))
}
for (i in 0.2) {
println(add(i, i))
}
Explanation: The 0..2 range counts from 0 to 2.
3 In the conventional order, in which sequence are operations added?
- divide, multiply, subtract, add
- subtract, multiply, divide, add
- add, subtract, multiply, divide Correct answer
- multiply, divide, add, subtract
Explanation: Addition, subtraction, multiplication, division is the common order.