0
0
Kotlinprogramming~30 mins

Vararg parameters in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Vararg Parameters in Kotlin
📖 Scenario: You are building a simple Kotlin program to handle a list of exam scores for students. Sometimes, you want to pass multiple scores at once to calculate their average.
🎯 Goal: Create a Kotlin function that uses vararg parameters to accept multiple exam scores and calculate their average.
📋 What You'll Learn
Create a function named averageScore that accepts multiple Int scores using vararg.
Inside the function, calculate the average of all scores passed.
Call the function with exactly these scores: 70, 85, 90, 75.
Print the average score as a Double.
💡 Why This Matters
🌍 Real World
Vararg parameters let you write flexible functions that can take any number of inputs, like scores, names, or prices, without needing to create arrays manually.
💼 Career
Understanding vararg parameters is useful for Kotlin developers working on apps that process lists of data dynamically, such as user inputs, sensor readings, or batch operations.
Progress0 / 4 steps
1
Create a function with vararg parameter
Write a Kotlin function named averageScore that takes a vararg parameter called scores of type Int. The function should return a Double. For now, just return 0.0 inside the function.
Kotlin
Need a hint?

Use vararg before the parameter name to accept multiple values.

2
Calculate the sum of all scores
Inside the averageScore function, create a variable named sum that adds all values in scores using a for loop.
Kotlin
Need a hint?

Use a for loop to add each score to sum.

3
Calculate and return the average
Modify the averageScore function to return the average of all scores as a Double. Use sum and the size of scores.
Kotlin
Need a hint?

Convert sum to Double before dividing by scores.size.

4
Call the function and print the result
Call the averageScore function with the scores 70, 85, 90, and 75. Print the returned average.
Kotlin
Need a hint?

Use println to show the average returned by averageScore.