Lab One
21 Sep 2025
Writing a Simple Program
- Write a Go program to display your name. Use the
fmt
package for output.
- Write a program that requests 5 integers from the user and then displays the mean (and if you have the appropriate knowledge – also the mode and median) of the values entered.
(Note, /
is used for division)
- Write a function which prompts for a number, and returns this to the main program.
If the number is even, produce a twenty-row multiplication table for the number.
If the entered value is odd, produce a table containing the first thirty integers not divisible by the entered value.
(Note, %
produces the modulus, or remainder, for integer division)
Please enter a number: 3
1
2
4
5
7
8
10
11
13
...
Please enter a number: 2
1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
4 x 2 = 8
5 x 2 = 10
...
Go I/O Examples
Use these examples as references for different input methods in Go.
// reading different types
var i int
var f float64
var s, word string
fmt.Scan(&i, &f, &s, &word)
fmt.Println(i, f, s, word)
// reading an int with error checking
reader := bufio.NewReader(os.Stdin)
var i int
for {
fmt.Print("Enter an integer: ")
_, err := fmt.Fscan(reader, &i)
if err == nil {
break
}
fmt.Println("Invalid input. Try again.")
reader.ReadString('\n') // clear buffer
}
fmt.Println(i)
// reading a single word
var word string
fmt.Scan(&word)
fmt.Println(word)
// reading a full line
line, _ := reader.ReadString('\n')
fmt.Println(line)
// reading character by character
for {
ch, _, err := reader.ReadRune()
if err != nil {
break
}
fmt.Printf("Char: %c\n", ch)
}
The pkg.go.dev/fmt and pkg.go.dev/bufio documentation are good starting points for Go input/output details.