0
0
Goprogramming~20 mins

Function declaration in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a function returning multiple values
What is the output of this Go program?
Go
package main
import "fmt"

func divideAndRemainder(a, b int) (int, int) {
    return a / b, a % b
}

func main() {
    q, r := divideAndRemainder(17, 5)
    fmt.Println(q, r)
}
A3 1
B4 2
C3 2
DError: multiple return values not handled
Attempts:
2 left
💡 Hint
Remember that 17 divided by 5 is 3 with remainder 2.
Predict Output
intermediate
2:00remaining
Output of a function with named return values
What does this Go program print?
Go
package main
import "fmt"

func swap(x, y string) (a, b string) {
    a = y
    b = x
    return
}

func main() {
    a, b := swap("hello", "world")
    fmt.Println(a, b)
}
Aworld world
Bhello world
Chello hello
Dworld hello
Attempts:
2 left
💡 Hint
Named return values are assigned inside the function before return.
Predict Output
advanced
2:00remaining
Output of recursive function calculating factorial
What is the output of this Go program?
Go
package main
import "fmt"

func factorial(n int) int {
    if n <= 1 {
        return 1
    }
    return n * factorial(n-1)
}

func main() {
    fmt.Println(factorial(5))
}
A120
B24
CError: stack overflow
D5
Attempts:
2 left
💡 Hint
Factorial of 5 is 5*4*3*2*1.
Predict Output
advanced
2:00remaining
Output of function with variadic parameters
What does this Go program print?
Go
package main
import "fmt"

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func main() {
    fmt.Println(sum(1, 2, 3, 4))
}
A10
B24
CError: cannot use ... with int
D0
Attempts:
2 left
💡 Hint
Sum all numbers passed as arguments.
Predict Output
expert
2:00remaining
Output of function returning a closure capturing variable
What is the output of this Go program?
Go
package main
import "fmt"

func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    counter := makeCounter()
    fmt.Println(counter())
    fmt.Println(counter())
    fmt.Println(counter())
}
AError: cannot return closure
B
1
2
3
C
1
1
1
D
0
1
2
Attempts:
2 left
💡 Hint
Closures remember the variable state between calls.