0
0
Goprogramming~10 mins

Return inside loops in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the first even number from the slice.

Go
func firstEven(nums []int) int {
    for _, num := range nums {
        if num%2 == 0 {
            return [1]
        }
    }
    return -1
}
Drag options to blanks, or click blank then click option'
Anum
Bnums
C0
Dnum + 1
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Returning the entire slice instead of the current number.
Returning a fixed number like 0 instead of the actual even number.
2fill in blank
medium

Complete the code to return true if any number in the slice is negative.

Go
func hasNegative(nums []int) bool {
    for _, n := range nums {
        if n < 0 {
            return [1]
        }
    }
    return false
}
Drag options to blanks, or click blank then click option'
A0
Btrue
Cn
Dfalse
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Returning the number itself instead of a boolean.
Returning false inside the loop which stops the check prematurely.
3fill in blank
hard

Fix the error in the code to return the index of the first zero in the slice.

Go
func firstZeroIndex(nums []int) int {
    for i, val := range nums {
        if val == 0 {
            return [1]
        }
    }
    return -1
}
Drag options to blanks, or click blank then click option'
Anums[i]
Bval
Ci
D0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Returning the value instead of the index.
Returning a fixed number like 0 regardless of the position.
4fill in blank
hard

Fill both blanks to return the sum of positive numbers only.

Go
func sumPositive(nums []int) int {
    sum := 0
    for _, n := range nums {
        if n [1] 0 {
            sum += [2]
        }
    }
    return sum
}
Drag options to blanks, or click blank then click option'
A>
Bn
C<
D0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using '<' instead of '>' causing wrong numbers to be summed.
Adding zero instead of the number.
5fill in blank
hard

Fill all three blanks to create a function that returns the first string longer than 3 characters.

Go
func firstLongString(words []string) string {
    for _, w := range words {
        if len([1]) [2] [3] {
            return w
        }
    }
    return ""
}
Drag options to blanks, or click blank then click option'
Aw
B>
C3
Dwords
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Checking length of the entire slice instead of the current word.
Using '<' instead of '>' causing wrong results.