Student Gradebook

Structs with methods that calculate averages and letter grades.

package main

import "fmt"

type Student struct {
	Name   string
	Grades []int
}

func (s Student) Average() float64 {
	if len(s.Grades) == 0 {
		return 0
	}
	total := 0
	for _, g := range s.Grades {
		total = total + g
	}
	return float64(total) / float64(len(s.Grades))
}

func (s Student) Letter() string {
	avg := s.Average()
	switch {
	case avg >= 90:
		return "A"
	case avg >= 80:
		return "B"
	case avg >= 70:
		return "C"
	default:
		return "F"
	}
}

func main() {
	students := []Student{
		{Name: "Alice", Grades: []int{92, 88, 95}},
		{Name: "Bob", Grades: []int{78, 82, 74}},
		{Name: "Carol", Grades: []int{65, 70, 68}},
	}

	for _, s := range students {
		fmt.Printf("%s: avg %.1f (%s)\n", s.Name, s.Average(), s.Letter())
	}
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy