Find Element Position in Array

Find Element Position in Array

Easy C++ Arrays 34 views
Explanation Complexity

Problem Statement

Search for a specific element and return its position (index). If not found, return -1. This teaches linear search concept.

Logic: Compare each element with search value

Input Format

An integer n (size of array)
Then n integers
Then an integer key (value to search)

Output Format

Index of the element if found (0-based)
OR
-1 if not found

Example

5
10 20 30 40 50
30
2

Constraints

• n ≥ 1

• Linear search (no sorting, no extra data structures)

Concept Explanation

Linear search checks each element one by one until the value is found or the array ends.

Step-by-Step Explanation

1.Read array size n and the elements.

2.Read the search value key.

3.Traverse the array from index 0 to n-1.

4.For each index i:

• If arr[i] == key, print i and stop.

5.If traversal ends without a match, print -1.

Concept Explanation

Linear search checks each element one by one until the value is found or the array ends.

Step-by-Step Explanation

1.Read array size n and the elements.

2.Read the search value key.

3.Traverse the array from index 0 to n-1.

4.For each index i:

• If arr[i] == key, print i and stop.

5.If traversal ends without a match, print -1.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers
Then an integer key (value to search)
Output Format
Index of the element if found (0-based)
OR
-1 if not found
Constraints
• n ≥ 1

• Linear search (no sorting, no extra data structures)

Examples

Input:
5 10 20 30 40 50 30
Output:
2

Example Solution (Public)

C++
void question5_find_position() {
    int arr[] = {12, 45, 67, 23, 89};
    int size = 5;
    int searchElement = 67;
    int position = -1;
    
    for(int i = 0; i < size; i++) {
        if(arr[i] == searchElement) {
            position = i;
            break;
        }
    }
    
    if(position != -1) {
        cout << "Element found at index: " << position << endl;
    } else {
        cout << "Element not found" << endl;
    }
}

Official Solution Code

void question5_find_position() {
    int arr[] = {12, 45, 67, 23, 89};
    int size = 5;
    int searchElement = 67;
    int position = -1;
    
    for(int i = 0; i < size; i++) {
        if(arr[i] == searchElement) {
            position = i;
            break;
        }
    }
    
    if(position != -1) {
        cout << "Element found at index: " << position << endl;
    } else {
        cout << "Element not found" << endl;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.