Grading scores example (golang)

vegaseat 1 Tallied Votes 817 Views Share

This time just a simple example of grading scores (0 - 100) with letters (A - F). Two approaches are presented, one using switch/case in an "on the fly" function, and the other uses the score as an index to a string of letters F through A.

// GradeLetter1.go
//
// A CS professor gives 100-point exams that are graded on the scale 
// 90-100:A, 80-89:B, 70-79:C, 60-69:D, 50-59:E, <50:F 
// Write a program that accepts an exam score and prints out the
// corresponding grade
//
// a look at switch/case and strings.Repeat()

package main

import "fmt"
import s "strings"

func main() {
	fmt.Println("Grading scores:")
	
	getGrade := func(score int) string {
		switch {
		case score >= 90: return "A"
		case score >= 80: return "B"
		case score >= 70: return "C"
		case score >= 60: return "D"
		case score >= 50: return "E"
		case score < 50: return "F"
		}
		return "check score value"
	}
	// testing ...
	scores := []int {49, 97, 71, 69, 80, 50}
	for _, score := range scores {
		grade := getGrade(score)
		fmt.Printf("Score %v = grade %s\n", score, grade)
	}

    fmt.Println(s.Repeat("-", 20))
	
	// another option ...
	gradeStr := s.Repeat("F", 50) + s.Repeat("E", 10) + s.Repeat("D", 10) +
	    s.Repeat("C", 10) + s.Repeat("B", 10) + s.Repeat("A", 11)
	for _, score := range scores {
		// use score as the index of the gradeStr
		grade := gradeStr[score]
		fmt.Printf("Score %v = grade %c\n", score, grade)
	}	
	//println(gradeStr)  // test
		
}

/*
Grading scores:
Score 49 = grade F
Score 97 = grade A
Score 71 = grade C
Score 69 = grade D
Score 80 = grade B
Score 50 = grade E
--------------------
Score 49 = grade F
Score 97 = grade A
Score 71 = grade C
Score 69 = grade D
Score 80 = grade B
Score 50 = grade E
*/
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

import s "strings"means that s is an alias for package "strings", saves you some typing.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.