Kotlin Function: Add two numbers with an explicit return type
Kotlin Function: Exercise-16 with Solution
Write a Kotlin function that takes two numbers as arguments and returns their sum. Explicitly specify the return type.
Sample Solution:
Kotlin Code:
fun calculateSum(num1: Int, num2: Int): Int {
return num1 + num2
}
fun main() {
val sum = calculateSum(7, 9)
println("Sum: $sum")
}
Sample Output:
Sum: 16
Explanation:
In the above exercise -
- The "calculateSum()" function takes two parameters num1 and num2, both of type Int. Inside the function, it calculates the sum of the two numbers by adding them together.
- The function's return type is explicitly specified as Int. After addition, the function returns the sum as an integer value.
- In the main function, we call the calculateSum function with arguments 7 and 9. The returned sum is stored in the sum variable. Finally, we print the sum value using println().
Kotlin Editor:
Previous: Print asterisk pattern.
Next: Check Prime Number, Return Boolean.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/kotlin-exercises/function/kotlin-function-exercise-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics