Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the index i instead of the element arr[i].
Returning size or 0 which are unrelated.
✗ Incorrect
We return the actual even number found, which is arr[i].
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
Return true immediately when a negative number is found.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning arr[i] which is zero instead of the index.
Returning 0 or -1 incorrectly inside the loop.
✗ Incorrect
We return the index i where zero is found, not the element arr[i].
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Returning arr[i] instead of sum.
Using -= instead of += to add values.
✗ Incorrect
Return the current sum when zero is found, and add positive numbers to sum using +=.
5fill in blank
hardComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of brackets to access characters.
Returning str instead of the character c.
✗ Incorrect
Use brackets [ ] to access characters by index and return the character c when it is a vowel.