Challenge - 5 Problems
Go Output Formatting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2: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) }
Attempts:
2 left
๐ก Hint
Look at the %.2f format specifier. It controls how many decimal places are shown.
โ Incorrect
The %.2f format prints the floating-point number rounded to 2 decimal places. So 3.14159 becomes 3.14.
โ Predict Output
intermediate2: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) }
Attempts:
2 left
๐ก Hint
The %10s means right-align in 10 spaces, %-10s means left-align in 10 spaces.
โ Incorrect
The first %10s prints the string right-aligned in 10 spaces, so spaces come first. The second %-10s prints left-aligned, so spaces come after.
โ Predict Output
advanced2: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) }
Attempts:
2 left
๐ก Hint
fmt.Sprintf formats the string with the given values replacing %d verbs.
โ Incorrect
Each %d is replaced by the corresponding integer argument. So 7, 5, and 12 (7+5) are inserted.
โ Predict Output
advanced2: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) }
Attempts:
2 left
๐ก Hint
Check if the number of verbs matches the number of arguments.
โ Incorrect
The format string expects two arguments (%d and %s), but only one (10) is given. This causes a runtime error.
๐ง Conceptual
expert3: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) }
Attempts:
2 left
๐ก Hint
Each %v corresponds to one argument. The last argument is the whole slice.
โ Incorrect
The code prints four items: the three integers and then the slice printed as [1 2 3].