0
0
Goprogramming~20 mins

Output formatting basics in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Output Formatting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Go code using fmt.Printf?
Consider the following Go code snippet. What will it print to the console?
Go
package main

import "fmt"

func main() {
    x := 42
    y := 3.14159
    fmt.Printf("x = %d, y = %.2f\n", x, y)
}
Ax = 42, y = 3.1416
Bx = 42, y = 3.14159
Cx = 42, y = 3.14
Dx = 42, y = 3.1
Attempts:
2 left
๐Ÿ’ก Hint
Look at the %.2f format specifier. It controls how many decimal places are shown.
โ“ Predict Output
intermediate
2:00remaining
What does this Go code print with width formatting?
What is the output of this Go program that uses width specifiers in fmt.Printf?
Go
package main

import "fmt"

func main() {
    name := "Go"
    fmt.Printf("|%10s|%-10s|\n", name, name)
}
A| Go|Go |
B|Go | Go|
C| Go |Go |
D| Go| Go|
Attempts:
2 left
๐Ÿ’ก Hint
The %10s means right-align in 10 spaces, %-10s means left-align in 10 spaces.
โ“ Predict Output
advanced
2:00remaining
What is the output of this Go code using fmt.Sprintf with multiple verbs?
What string does this Go code produce?
Go
package main

import "fmt"

func main() {
    s := fmt.Sprintf("%d + %d = %d", 7, 5, 7+5)
    fmt.Println(s)
}
A7 + 5 = 0
B7 + 5 = 7+5
C7 + 5 = 75
D7 + 5 = 12
Attempts:
2 left
๐Ÿ’ก Hint
fmt.Sprintf formats the string with the given values replacing %d verbs.
โ“ Predict Output
advanced
2:00remaining
What error does this Go code produce?
What happens when you run this Go code?
Go
package main

import "fmt"

func main() {
    fmt.Printf("%d %s", 10)
}
A10 %s
Bruntime error: missing argument for %s
C10
DCompilation error: wrong number of arguments
Attempts:
2 left
๐Ÿ’ก Hint
Check if the number of verbs matches the number of arguments.
๐Ÿง  Conceptual
expert
3:00remaining
How many items are printed by this Go code with fmt.Printf and a slice?
What is the output count of items printed by this Go code snippet?
Go
package main

import "fmt"

func main() {
    nums := []int{1, 2, 3}
    fmt.Printf("%v %v %v %v", nums[0], nums[1], nums[2], nums)
}
APrints 4 items: 1 2 3 [1 2 3]
BPrints 3 items: 1 2 3
CPrints 1 item: [1 2 3]
DCompilation error: cannot print slice with %v
Attempts:
2 left
๐Ÿ’ก Hint
Each %v corresponds to one argument. The last argument is the whole slice.