Description
Let we have arr[] = {1, 5 , 8, 6 , 4} and 1)we have to find 8 then our output will be 'Element 8 is present at position 3' 2)we have to find 3 then our output will be 'Element 3 not present in this list' Process 1) start traversing from index 0 to last index and compare the required element with each element. 2) if required element present then print element present. 3) if required element not present the print element is not present in the list.
C/C++
/* C Program to Search for an Element in an Array */ //Save it as LinearSearch.c #include<stdio.h> int main(){ int i, n, number; printf("Enter the no of elements of an array : "); scanf("%d",&n); int arr[n]; printf("Enter the elements of array : "); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Enter the elements you want to find : "); scanf("%d",&number); int found=0,position=0; for(i=0;i<n;i++) { if(arr[i] == number) { found = 1; position = i; break; } else { found = 0; } } if(found == 1) { printf("Element %d found at postion %d", number, (position+1)); } else { printf("Element %d not present in this list", number); } }
Input: Enter the size of array : 5 Enter the elements : 3 9 2 7 5 Enter the element to search : 7 Output: The element 7 is found at 4
Java
/* Java Program to Search for an Element in an Array */ //Save it as LinearSearch.java import java.io.*; import java.util.*; class LinearSearch { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the no of elements of an array : "); int n = scanner.nextInt(); int arr[] = new int[n]; System.out.println("Enter the elements of array : "); for(int i=0;i<n;i++) { arr[i] = scanner.nextInt(); } System.out.println("Enter the elements you want to find : "); int number = scanner.nextInt(); int found=0,position=0; for(int i=0;i<n;i++) { if(arr[i] == number) { found = 1; position = i; break; } else { found = 0; } } if(found == 1) { System.out.println("Element " + number+" found at postion "+ (position+1)); } else { System.out.println("Element "+number+" not present in this list"); } } }
Input: Enter the size of array : 5 Enter the elements : 3 9 2 7 5 Enter the element to search : 7 Output: The element 7 is found at 4
Related Programs
1) Program for finding Second Largest Element Of Array2) Program to form a number using entered digits
3) Program to merge two sorted arrays
4) Program to Rearrange an array such that arr[i]=i
5) Program to Reverse an Array using Recursion
6) Program to Find the smallest missing number
7) Program to Find missing odd number in first n odd number
8) Program to Find Value equal to index value
9) Program to Check Array is Perfect or Not
10) Program to make pair of elements alternatively