0
0
Goprogramming~20 mins

Why functions are needed in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Mastery Badge
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 program using a function?
Look at this Go program. What will it print when run?
Go
package main
import "fmt"
func greet(name string) string {
    return "Hello, " + name + "!"
}
func main() {
    message := greet("Alice")
    fmt.Println(message)
}
AAlice
Bgreet
CHello, !
DHello, Alice!
Attempts:
2 left
💡 Hint
The function greet returns a greeting message with the name included.
🧠 Conceptual
intermediate
1:30remaining
Why use functions in programming?
Which of these is the main reason to use functions in programs?
ATo confuse the reader with extra code
BTo make the program run slower
CTo repeat the same code many times without rewriting it
DTo avoid using variables
Attempts:
2 left
💡 Hint
Think about how functions help with repeating tasks.
Predict Output
advanced
2:00remaining
What is the output of this Go program with multiple function calls?
What will this Go program print when run?
Go
package main
import "fmt"
func add(a, b int) int {
    return a + b
}
func main() {
    x := add(2, 3)
    y := add(x, 4)
    fmt.Println(y)
}
A7
B9
C5
DError
Attempts:
2 left
💡 Hint
Add the numbers step by step.
🔧 Debug
advanced
2:00remaining
What error does this Go program cause?
This Go program tries to use a function but has a problem. What error will it cause?
Go
package main
import "fmt"
func multiply(a int, b int) int {
    return a * b
}
func main() {
    result := multiply(3)
    fmt.Println(result)
}
Acompile error: missing argument for multiply
Bprints 3
Cruntime error: nil pointer dereference
Dprints 0
Attempts:
2 left
💡 Hint
Check how many arguments the multiply function needs.
🚀 Application
expert
2:30remaining
How many times is the function called in this Go program?
Count how many times the function 'countCalls' is called when this program runs.
Go
package main
import "fmt"
var calls int
func countCalls() {
    calls++
}
func main() {
    for i := 0; i < 3; i++ {
        countCalls()
    }
    if calls > 0 {
        countCalls()
    }
    fmt.Println(calls)
}
A4
B3
C1
D0
Attempts:
2 left
💡 Hint
Count calls inside the loop and the one after the loop.