Extend your head command to take an integer n and return the first n lines of lines, joined by newline characters (\n). For this version you may assume 0 ≤ n ≤ len(lines). If n is 0 the result is the empty string.
Function signature:
func head(lines []string, n int) string
Example:
Input: lines = ["alpha", "beta", "gamma", "delta", "epsilon"], n = 3 Output: "alpha\nbeta\ngamma" When printed: alpha beta gamma
Loop with
i from 0 to n - 1, accumulating each line into a string. Insert a "\n" before every line except the first.
for i := 0; i < n; i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
The full solution:
func head(lines []string, n int) string {
result := ""
for i := 0; i < n; i++ {
if i > 0 {
result += "\n"
}
result += lines[i]
}
return result
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
