C Program to Search for a given Element in an Array.

Problem Statement: You are given an array of integers and a target element. Your task is to find if the target element exists in the array or not. Write a C program to search the element.

Example:

Suppose we have an array arr[] = {2, 4, 6, 8, 10}, and the target element is 6. The program should output "Element found" since 6 is present in the array.


Linear Searching Algorithm.

Below is the step-by-step algorithm to search for an element from the given array if exists:

Step 1: Start with the first element of the array and compare it with the target element.

Step 2: If the current element is equal to the target element, return "Element found".

Step 3: If the current element is not equal to the target element, move on to the next element in the array.

Step 4: Repeat steps 2 and 3 until you find the target element or reach the end of the array.

Step 5: If the end of the array is reached and the target element is not found, return "Element not found".


Program to search an element in the given array.

//C program to search an element from the given array
#include <stdio.h>

int searchElement(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return 1; // Element found
        }
    }
    return 0; // Element not found
}

int main() {
    int arr[] = {2, 4, 6, 8, 10};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 6;

    if (searchElement(arr, size, target)) {
        printf("Element found\n");
    } else {
        printf("Element not found\n");
    }

    return 0;
}
Output:
Element found

Time Complexity: The time complexity of this algorithm is O(n) because, in the worst-case scenario, we might have to check all the elements of the array to find the target element.

Space Complexity: The space complexity of this algorithm is O(1) as it uses a constant amount of extra space to store the loop variable and other variables.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS