0
0
DSA C++programming~10 mins

Linear Search Algorithm in DSA C++ - Interactive Practice

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

Complete the code to return the index of the target element in the array or -1 if not found.

DSA C++
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == [1]) {
            return i;
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Btarget
Cn
Darr[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Using the loop index i instead of the target value in the comparison.
Comparing arr[i] to itself instead of the target.
2fill in blank
medium

Complete the code to loop through the array correctly for linear search.

DSA C++
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < [1]; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Btarget
Carr
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using the target value as the loop limit.
Using the loop index variable as the limit.
3fill in blank
hard

Fix the error in the return statement to indicate the target was not found.

DSA C++
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) {
            return i;
        }
    }
    return [1];
}
Drag options to blanks, or click blank then click option'
A-1
B0
Ci
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the loop index i after the loop ends.
Returning zero which could be a valid index.
4fill in blank
hard

Fill both blanks to create a linear search that returns true if the target is found, false otherwise.

DSA C++
bool linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < [1]; i++) {
        if (arr[i] == [2]) {
            return true;
        }
    }
    return false;
}
Drag options to blanks, or click blank then click option'
An
Btarget
Ci
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong variable for loop limit.
Comparing to the loop index instead of the target.
5fill in blank
hard

Fill all three blanks to create a linear search that returns the index or -1 if not found, using a while loop.

DSA C++
int linearSearch(int arr[], int n, int target) {
    int i = 0;
    while (i [1] n) {
        if (arr[i] == [2]) {
            return [3];
        }
        i++;
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
A<
Btarget
Ci
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= instead of < in the loop condition causing out-of-bounds access.
Returning the target value instead of the index.