CSI 2120

Lab 1: Go

This lab is based on the tutorial called A tour of Go on golang.org. You are expected to work though the sections titled Basics and then solve the problems below. You can directly use the on-line go interpreter, called the sandbox, to try your programs.

Exercise 1: Go Basics: Functions

Read the section on Packages, variables, and functions.

Write a function in Go that takes as input a float variable and returns two integer values. One integer value which is the floor of the float value and the second integer value which is the ceiling of the float value. Print the result to console.

Exercise 2: Go Basics: Looping

Read the section on Flow control statements: for, if, else, switch and defer.

A program should print a pattern as follows to the console:


    x
   xx
  xxx
 xxxx
xxxxx
 xxxx
  xxx
   xx
    x
Add two loops to the following program. The first loop should increase the "x" in lineSymb until the number of "x" is equal to
lineWidth
. The second loop should reduce the number of "x" until only one "x" is left.

package main

import "fmt"

func main() {
	lineWidth := 5
	symb := "x"
	lineSymb := symb
	formatStr := fmt.Sprintf("%%%ds\n", lineWidth)
        fmt.Printf(formatStr, lineSymb)
}

Exercise 3: Go Basics: Structs and Pointers

Read the section on More types: structs, slices, and maps..

A Go program is to read a person (last and first name) from console (use an input array if using the sandbox) and assign an Id counting up. The program must use the structure Person.

type Person struct {
	lastName  string
	firstName string
	iD        int
}
The main function looks as follows:

func main() {
	nextId := 101
	for {
		var (
			p   Person
			err error
		)
		nextId, err = inPerson(&p, nextId)
		if err != nil {
			fmt.Println("Invalid entry ... exiting")
			break
		}
		printPerson(p)
	}
}
Supply the functions inPerson and printPerson.

Exercise 4: Maps

Create a map that uses a string representing a course code as key. The value in the map needs to be a structure with basic information about the course. The following main routine:


import "fmt"
    
// Define a suitable structure 

func main() {
	// Create a dynamic map m

	// Add the courses CSI2120 and CSI2110 to the map 

	
	for k, v := range m {
		fmt.Printf("Course Code: %s\n", k)
		fmt.Printf("Number of students: %d\n", v.NStudents)
		fmt.Printf("Professor: %s\n", v.Professor)
		fmt.Printf("Average: %f\n\n", v.Avg)
	}
}
must print:

Course Code: CSI2110
Number of students: 186
Professor: Lang
Average: 79.500000

Course Code: CSI2120
Number of students: 211
Professor: Moura
Average: 81.000000