Chapter 2 - Conditionals and Loops

Exercise 2: if Statements

We’re writing a program that asks the user for a racer’s name and the position they finished the race in, and prints out what type of medal they should get.

The final call to fmt.Println at the bottom includes a variable that you needed to declare and assign a value to.

Solution

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter racer name: ")
	name, err := reader.ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}
	name = strings.TrimSpace(name)

	fmt.Print("Enter racer rank: ")
	input, err := reader.ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}
	input = strings.TrimSpace(input)
	rank, err := strconv.ParseInt(input, 10, 64)
	if err != nil {
		log.Fatal(err)
	}

	// Need to declare "medal" outside the "if" statements,
	// so that it's still in scope afterwards.
	var medal string
	if rank == 1 {
		medal = "gold"
	} else if rank == 2 {
		medal = "silver"
	} else if rank == 3 {
		medal = "bronze"
	} else { // Runs if none of the above are true.
		medal = "participant"
	}

	fmt.Println(name, "gets a", medal, "medal!")
}

Example output:

Enter racer name: Noam
Enter racer rank: 1
Noam gets a gold medal!