0
0
C++programming~10 mins

Return inside loops in C++ - 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 array.

C++
int firstEven(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        if (arr[i] % 2 == 0) {
            return [1];
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Aarr[i]
Bi
C0
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the index i instead of the element arr[i].
Returning size or 0 which are unrelated.
2fill in blank
medium

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

C++
bool hasNegative(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        if (arr[i] < 0) {
            return [1];
        }
    }
    return false;
}
Drag options to blanks, or click blank then click option'
Afalse
Btrue
Carr[i]
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning false inside the loop when a negative is found.
Returning the element arr[i] instead of a boolean.
3fill in blank
hard

Fix the error in the code to return the index of the first zero in the array, or -1 if none.

C++
int findZero(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == 0) {
            return [1];
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
A-1
Barr[i]
C0
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Returning arr[i] which is zero instead of the index.
Returning 0 or -1 incorrectly inside the loop.
4fill in blank
hard

Fill both blanks to return the sum of positive numbers in the array, stopping early if a zero is found.

C++
int sumPositives(int arr[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] == 0) {
            return [1];
        }
        if (arr[i] > 0) {
            sum [2] arr[i];
        }
    }
    return sum;
}
Drag options to blanks, or click blank then click option'
Asum
B+=
C-=
Darr[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Returning arr[i] instead of sum.
Using -= instead of += to add values.
5fill in blank
hard

Complete the code to return the first character in the string that is a vowel, or '\0' if none.

C++
char firstVowel(const char* str) {
    for (int i = 0; str[i] != '\0'; i++) {
        char c = str[i];
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
            return [1];
        }
    }
    return '\0';
}
Drag options to blanks, or click blank then click option'
A[
B]
Cc
Dstr
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of brackets to access characters.
Returning str instead of the character c.