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; }
Element found
No comments:
Post a Comment