Recap - Simple Calculator
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 34 of 93.
Challenge
EasyWrite a function calculate that takes a, b, and operation and returns the result of performing the specified operation on the two numbers.
Use if-else if-else chains to determine which arithmetic operation to perform based on the operation string.
Conditions:
- If
operationis"add", return the sum ofaandb - If
operationis"subtract", returnaminusb - If
operationis"multiply", return the product ofaandb - If
operationis"divide", returnadivided byb(integer division) - For any other operation, return
0
Parameters:
a(Int): The first numberb(Int): The second numberoperation(String): The operation to perform
Returns: The result of the calculation, or 0 if the operation is not recognized (Int)
Input constraints: For division, the second number is nonzero. All inputs and intermediate results fit in the declared numeric type.
Try it yourself
fun calculate(a: Int, b: Int, operation: String): Int {
// Write code here
}
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground