Challenge 1 - Combined program
- Go course
- Beginner
- Lesson 87/90
- 8 min
Write a program combining variables, loops and functions.
Challenge: grade statistics
You will combine variables, loops and functions. Write istatistik(notlar []int) (float64, int, int), which finds a grade list's average, highest grade and number of passing students (60 and above).
ort, enYuksek, gecen := istatistik([]int{45, 72, 90, 60, 38})
// 61 90 3For an empty list all three values must be 0; don't forget division by zero.
Plan
1) If len(notlar) == 0, return 0, 0, 0. 2) Declare toplam, enYuksek := notlar[0] and gecen. 3) Walk with range: sum, update the highest grade and count 60 and above. 4) Compute the average with float64(toplam) / float64(len(notlar)) and return the three values.
Practice Statistics function
Write the istatistik function following the plan. Print the results for []int{45, 72, 90, 60, 38} and an empty slice on separate lines.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func istatistik(notlar []int) (float64, int, int) {
if len(notlar) == 0 {
return 0, 0, 0
}
toplam, enYuksek, gecen := 0, notlar[0], 0
for _, n := range notlar {
toplam += n
if n > enYuksek {
enYuksek = n
}
if n >= 60 {
gecen++
}
}
return float64(toplam) / float64(len(notlar)), enYuksek, gecen
}
func main() {
fmt.Println(istatistik([]int{45, 72, 90, 60, 38}))
fmt.Println(istatistik(nil))
}Expected output
61 90 3 0 0 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is the empty-list check done at the very start of the function?
- The average divides by len(notlar); dividing by 0 produces NaN Correct answer
- Because it's shorter
- Go requires it
- It isn't needed
Explanation: float64(0)/float64(0) gives NaN; an early return handles this edge case cleanly.
2 Update the highest grade
for _, n := range notlar {
if n ____ enYuksek {
enYuksek = n
}
}
for _, n := range notlar {
if n > enYuksek {
enYuksek = n
}
}
Explanation: When a larger grade is seen, the highest value is updated.
3 Input and result
| Term | Meaning |
|---|---|
[45 72 90 60 38] |
61 90 3 |
[] |
0 0 0 |
[100] |
100 100 1 |
[59 59] |
59 59 0 |